diff --git a/css/base.css b/css/base.css index f4ef024c..0463dc1b 100644 --- a/css/base.css +++ b/css/base.css @@ -321,6 +321,9 @@ ul.menu > li.separator:hover { opacity: 0; background-color: inherit; } +.menuTrigger a { + color: #757575; +} li .menuTrigger { top: 0.25rem; @@ -3030,7 +3033,6 @@ ul.tabbar li.active > a { display: flex; align-items: center; height: 100%; - margin-left: auto; margin-right: 1rem; } @@ -3192,7 +3194,7 @@ ul.phone-country-selector span.country { } .pinned { - min-width: 16rem; + min-width: 12rem; } } diff --git a/css/base.min.css b/css/base.min.css index 81f24f67..bccb0131 100644 --- a/css/base.min.css +++ b/css/base.min.css @@ -1 +1 @@ -*{box-sizing:border-box;font-family:Roboto,Arial,sans-serif;margin:0;padding:0;scrollbar-color:#0000004d #ffffff1a;scrollbar-width:thin;text-rendering:optimizeLegibility}body,html{background-color:silver;box-shadow:inset 0 10rem #3949ab;color:#666;font-size:10pt;height:100%;overflow:hidden;width:100%}tt{font-family:Roboto Mono,Courier,monospace}a{color:#2196f3;text-decoration:none}a:focus,a:hover{color:#0a6ebd;text-decoration:underline}a.danger{color:#d32f2f}a.danger:focus,a.danger:hover{color:#f44336}a.gray:focus,a.gray:hover{color:#999}form{line-height:1.5;padding:.5rem .75rem}form,label{font-size:1.1rem}label{margin-right:auto}label.small{color:#1e88e5;font-size:.95rem}label.large{color:#1e88e5;font-size:1.1rem}img.avatar{border-radius:50%;height:100%;width:100%}button{border:1px solid #0000;border-radius:4px;box-shadow:0 1px 3px 0 #00000040;cursor:pointer;display:inline-block;font-family:inherit;font-size:1.05rem;font-weight:400;height:2.2rem;line-height:2.2rem;margin:0 .35rem;min-width:5rem;padding-left:1.2rem;padding-right:1.2rem;text-align:center;text-transform:uppercase;touch-action:manipulation;vertical-align:middle;white-space:nowrap}button[disabled],html input[disabled]{box-shadow:none;cursor:default;filter:grayscale(50%);opacity:.65}button.round{border-radius:50%;box-shadow:0 2px .5rem 0 #00000040;height:3rem;line-height:3.5rem;margin:0;outline:none;padding:0;width:3rem;z-index:2}button.round.small{box-shadow:0 2px .35rem 0 #00000040;height:2rem;line-height:2rem;width:2rem}button:active:not([disabled]),button:hover:not([disabled]){color:#fff}button:active{box-shadow:inset 0 3px .5rem rgba(0,0,0,.125)}button:active.round.small{box-shadow:inset 0 2px .35rem rgba(0,0,0,.125)}button.primary{background-color:#1e88e5;color:#fff}button.primary:active:not([disabled]),button.primary:hover:not([disabled]){background-color:#2962ff}button.secondary{background-color:#fff;color:#2196f3}button.secondary:active:not([disabled]),button.secondary:hover:not([disabled]){background-color:#e3f2fd}button.outline{background-color:initial;border:1px solid silver;box-shadow:none;color:#2196f3}button.outline:active:not([disabled]),button.outline:hover:not([disabled]){background-color:#e8eaf6}button.danger{background-color:#ec6560;color:#fff}button.danger:active:not([disabled]),button.danger:hover:not([disabled]){background-color:#f77}button.positive{background-color:#71c46f;color:#fff}button.positive:active:not([disabled]),button.positive:hover:not([disabled]){background-color:#7fed7f}input,textarea{background:#0000;border:none;color:#666;font-family:inherit;font-size:1.1rem;margin:.25rem 0;outline:none;padding:0 .125rem}input[type=email],input[type=password],input[type=search],input[type=tel],input[type=text],textarea{border-bottom:1px solid #ccc;box-shadow:0 1px 0 #0000001a;height:2.5rem;transition:all .1s ease-in-out,height 0s}input[type=email],input[type=password],input[type=tel],input[type=text],textarea{width:100%}input[type=email]:focus,input[type=password]:focus,input[type=search]:focus,input[type=tel]:focus,input[type=text]:focus,textarea:focus{border-bottom:1px solid #2196f3;box-shadow:0 1px 0 #2196f340}input[type=email].invalid,input[type=password].invalid,input[type=search].invalid,input[type=tel].invalid,input[type=text].invalid,textarea.invalid{border-bottom:1px solid #e57373;box-shadow:0 1px 0 #e5737340}input[type=email]::placeholder,input[type=password]::placeholder,input[type=search]::placeholder,input[type=tel]::placeholder,input[type=text]::placeholder,textarea::placeholder{color:#bbb;font-weight:lighter}input[type=password].with-visibility,input[type=text].with-visibility{margin-right:-2rem;padding-right:2rem}textarea{padding-top:.45rem;resize:none}textarea.inplace-edit{font-size:unset;height:unset}::-webkit-scrollbar{width:.6rem}::-webkit-scrollbar-track{background-color:#ffffff1a;-webkit-box-shadow:inset 0 0 6px #0003;box-shadow:inset 0 0 6px #0003}::-webkit-scrollbar-thumb{background-color:#0000004d}ul.menu{background-color:#fff;border-radius:.2rem;box-shadow:0 1px 6px #00000073;list-style:none;padding-bottom:.35rem;padding-top:.35rem;position:absolute;width:12rem;z-index:4}ul.menu>li{cursor:pointer;padding:.75rem .75rem .75rem 1.25rem}ul.menu>li:hover{background-color:#f5f5f5}ul.menu>li.separator{height:1px;margin:2px;padding:0}ul.menu>li.separator,ul.menu>li.separator:hover{background-color:#ccc}.menuTrigger{background-color:inherit;border-radius:.7rem;height:1.4rem;line-height:1.4rem;opacity:0;position:absolute;right:.25rem;text-align:center;width:1.4rem}li .menuTrigger{top:.25rem}li:hover .menuTrigger{opacity:.9}li:hover .menuTrigger a{color:#757575}div.alert-container{align-items:center;background:#f0f0f0d9;display:flex;height:100%;justify-content:center;overflow:hidden;padding:1rem;position:absolute;width:100%;z-index:3}div.alert{background-color:#fff;border-radius:.3rem;box-shadow:.15rem .15rem 1.5rem #00000073;height:min-content;margin:auto 2rem;max-height:40rem;max-width:24rem;min-width:16rem;overflow:hidden;padding:1rem;position:relative;width:fit-content}div.alert-container .title{color:#2196f3;font-size:1.2rem;font-weight:500;padding:0 0 .35rem;position:relative;width:100%}div.alert-container .title.with-control{align-items:center;display:flex;flex:none;justify-content:space-between;padding:.5rem .5rem 0;position:relative}div.alert-container .content{padding:.5rem 0;position:relative}div.trusted-badge{margin:.25rem 0}.blue{color:#2196f3!important}.lt-blue{color:#64b5f6!important}.verified-color{color:#03a9f4!important}.staff-color{color:#689f38!important}.danger-color{color:#ffc107!important}.green{color:#388e3c}.white{color:#fff!important}.red{color:#d32f2f!important}.badge-inv{color:#fffd!important}.gray{color:#757575!important}.light-gray{color:#bbb!important}.large{font-size:120%}.small{font-size:90%}.float-right{position:absolute;right:.5rem}.hr{background-color:#f0f0f0;box-shadow:inset 0 .25rem .25rem -.25rem #00000026,inset 0 -.25rem .25rem -.25rem #00000026;display:block;height:.45rem;min-height:.3rem;width:100%}.hr.thin{height:.015rem}.ellipsized{overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.flat-button{align-items:center;background-color:#fff;display:flex;font-weight:400;height:2em;line-height:2em;margin:.15rem .35rem;text-align:center;text-transform:uppercase;touch-action:manipulation;vertical-align:middle;white-space:nowrap;z-index:1}.flat-button:focus,.flat-button:hover{text-decoration:none}.flat-button.faux{background-color:#eee;border:1px solid #999;border-radius:3px;display:inline-block;height:1.4em;line-height:1.4em;margin:.15rem;padding:0 .35rem;text-transform:none}.action-button{background-color:#fafafa;border-radius:50%;bottom:1rem;box-shadow:0 2px .5rem 0 #00000040;color:#999;display:block;font-size:1.8rem;height:3.25rem;margin:0;min-height:unset;min-width:unset;outline:none;padding:0;position:absolute;right:1rem;transition:all .15s;width:3.25rem;z-index:2}.action-button:focus,.action-button:hover{background-color:#f0f0f0;color:#888}.action-button:active{background-color:#eee;color:#777}.action-button.hidden{bottom:2.625rem;font-size:1px;height:1px;line-height:1px;opacity:0;right:2.625rem;width:1px}.group-focus{outline:none}#mountPoint{height:100%;padding-bottom:1rem;padding-top:1rem}#noscript-message{background-color:#fff;border-radius:.25rem;box-shadow:1px 2px .3rem gray;display:flex;flex-direction:column;margin-left:auto;margin-right:auto;margin-top:5rem;max-width:30rem;overflow:hidden;position:relative}#noscript-title{background-color:#2196f3;color:#bbdefb;font-size:120%;font-weight:bolder;padding:1rem}#noscript-content{padding:1rem}#app-container{background-color:#fff;border-radius:.25rem;box-shadow:1px 2px .3rem gray;display:flex;height:100%;margin-left:auto;margin-right:auto;max-width:84rem;overflow:hidden;position:relative}#sidepanel{flex-grow:0;flex-shrink:0.3;min-width:18rem;width:24rem}#sidepanel,#topic-view{display:flex;flex-direction:column;height:100%;position:relative}#topic-view{overflow-x:hidden;width:100%}#info-view{display:flex;flex-direction:column;flex-grow:0;flex-shrink:0.3;height:100%;min-width:18rem;width:24rem}.center-medium-text{align-items:center;display:flex;font-size:1.4rem;height:100%;justify-content:center;text-align:center;width:100%}.nodisplay{display:none!important}.quoted{margin-left:1rem}.space-right{margin-right:.25rem}.rounded-container{background-color:#fafafa;border-radius:.1rem;margin:.25rem;padding:.25rem;position:relative}.in-place-edit{border-bottom:1px dashed #ddd;cursor:pointer;display:inline-block;font-family:inherit;font-size:1rem;margin:.25rem .125rem 0;vertical-align:initial;width:100%}.in-place-edit.short{font-size:1.1rem;height:2.5rem;line-height:2.25}.in-place-edit.disabled{border-bottom:none;color:#888;cursor:default}.in-place-edit.placeholder{color:#bbb}.in-place-edit span{display:inline-block}.in-place-edit.short span{display:block;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}table.permission-editor{width:100%}table.permission-editor td{font-size:1.1rem;margin:.35rem 0;vertical-align:middle}table.permission-editor td.checkbox{color:#999;text-align:center}.permission-editor .material-icons{font-size:1.3rem;line-height:1.3rem}.material-icons.clickable{border-bottom:none;cursor:pointer}.clickable{border-bottom:1px dashed #ddd}.clean-clickable,.clickable,.image-clickable{cursor:pointer}.panel-title{font-size:1.4rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.panel-title.deleted{text-decoration:line-through}.caption-panel{box-shadow:0 1px 2px gray;flex:none;height:4rem;overflow-x:hidden;white-space:nowrap;z-index:1}.caption-panel,.dialog-buttons{align-items:center;display:flex;padding:.5rem}.dialog-buttons{justify-content:flex-end}.dialog-buttons button{margin:0 .5rem}.avatar-box{flex-grow:0;flex-shrink:0;position:relative}.bot-form{display:flex;flex-direction:column;line-height:2rem;min-width:8rem;overflow:hidden}.bot-form div{min-height:2rem;vertical-align:middle}.bot-form button{background-color:#eef;color:#2196f3;display:inline-block;font-size:inherit;height:2rem;line-height:2rem;margin:.15rem;text-transform:none}.bot-form>div>button{width:auto}.bot-form button:active,.bot-form button:focus,.bot-form button:hover{background-color:#e3f2fd;outline:0}#side-caption-panel{background-color:#2196f3;color:#bbdefb}#side-caption-panel a{color:#bbdefb;line-height:1;padding-left:.5rem}#side-caption-panel :hover{color:#fff}#sidepanel-title{margin-left:.5rem;margin-right:auto}#self-avatar{border-radius:50%;flex:none;height:3rem;min-width:3rem;width:3rem}#self-avatar.avatar-box{font-size:1.8rem}#settings-form ul{list-style:none}#settings-form li{vertical-align:middle}#settings-form label{display:inline-block;padding-left:.5rem}input#host-name{width:100%}input.search{text-indent:1.4rem}i.search{left:.6rem;position:absolute}.info-box{display:none;overflow:hidden;padding:1rem 1.5rem .75rem .5rem;position:relative}.info-box>span{line-height:1.35rem}.info-box .cancel{position:absolute;right:.25rem;top:.5rem}.info-box.error{background-color:#ffcdd2;border-bottom:1px solid #ffbfc8;color:#b71c1c;display:flex}.info-box.warning{background-color:#fff9c4;border-bottom:1px solid #fff59d;color:#6d4c41;display:flex}.info-box.info{background-color:#e1f5fe;border-bottom:1px solid #b3e5fc;color:#0288d1;display:flex}.info-box .cancel .material-icons{color:#757575;font-size:1rem}.info-box.error .cancel .material-icons{color:#b71c1c}.info-box .icon{display:block;margin-right:.5rem}.info-box .icon .material-icons{font-size:1.5rem}.info-box.warning .icon .material-icons{color:#fbc02d}.info-box.error .icon .material-icons{color:#ef5350}.info-box.info .icon .material-icons{color:#0288d1}.flex-column{display:flex;flex-direction:column;height:100%;overflow-x:hidden}.flex-column.narrow{height:auto}.scrollable-panel{height:100%;margin-bottom:auto;margin-top:.25rem;overflow-x:hidden;overflow-y:auto;scroll-behavior:smooth}.contact-box{list-style:none;overflow-x:hidden}.contact-box>li{background:linear-gradient(90deg,#0000 3.5rem,#eee 1px,#eee) 0 100% /100% 1px no-repeat,#fff;cursor:pointer;display:flex;flex-grow:0;flex-shrink:0;min-height:3.75rem;overflow-x:hidden;padding:.35rem .25rem .5rem .35rem;position:relative}.contact-box.small>li{min-height:2.5rem;padding:.25rem .25rem .35rem .35rem}.contact-box>li:last-child{background:#fff}.contact-box>li:hover{background-color:#eceff1}.contact-box>li.selected{background-color:#cfd8dc}.contact-box>li.action{border-bottom:none;min-height:2.5rem}.contact-box .text-box{overflow-x:hidden}.contact-box .contact-title{font-size:1.05rem;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.contact-box .contact-title.deleted{opacity:.66;text-decoration:line-through;text-decoration-thickness:.5px}.contact-box .contact-comment{font-weight:lighter}.contact-box .contact-comment,.contact-box .contact-comment>span{overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.contact-box .contact-comment b{font-weight:bolder}.contact-box .contact-comment .material-icons{color:#777;margin-bottom:.2rem}.contact-box .avatar-box{font-size:1.8rem;height:3rem;margin-right:.35rem;min-height:3rem;min-width:3rem;overflow:hidden;padding:0;position:relative;width:3rem}.contact-box .avatar{border-radius:50%;height:3rem;width:3rem}.contact-box.small .avatar-box{font-size:1.2rem;height:2rem;min-height:2rem;min-width:2rem;width:2rem}.contact-box.small .avatar{height:2rem;width:2rem}.avatar.deleted{filter:grayscale(1);opacity:.75}.contact-box .avatar-box>.material-icons{display:flex;flex-direction:column;font-size:2.4rem;justify-content:space-around;line-height:3rem}.contact-box.small .avatar-box>.material-icons{font-size:1.6rem;line-height:2rem}.contact-box .text-box{display:flex;flex-direction:column;justify-content:space-around}.contact-box .text-box>div{align-items:center;display:flex;flex-direction:row}.contact-box .action-text{cursor:pointer;font-size:.95rem;line-height:2.5rem;margin:0 auto;text-align:center}img.channel{height:1.25rem;margin-left:.3rem;vertical-align:middle;width:1.25rem}.large img.channel{height:1.45rem;margin-bottom:.15rem;margin-left:.5rem;width:1.45rem}.avatar-box .online,.offline{border-radius:50%;bottom:.1rem;flex-shrink:0;height:.75rem;min-height:.75rem;min-width:.75rem;position:absolute;right:0;width:.75rem}.avatar-box .online{background-color:#4caf50}.avatar-box .offline{background-color:silver}.online.typing{animation:typing .5s infinite}@keyframes typing{0%,to{transform:translateX(0)}50%{transform:translateX(-.3rem)}}.contact-box .checkmark.material-icons{border:0 solid #0000;color:#0097a7;overflow:visible;padding-left:.5px}.contact-box .checkmark.material-icons,.contact-box .deleted.material-icons{background-color:#fff;bottom:0;font-size:1.5rem;height:1.5rem;position:absolute;right:0;width:1.5rem}.contact-box .deleted.material-icons{color:#999}#add-topic{bottom:1rem;position:absolute;right:1rem}.panel-form{display:flex;flex-direction:column;padding:0;position:relative}.panel-form-row{align-items:center;flex-shrink:0}.panel-form-column,.panel-form-row{display:flex;flex-grow:0;line-height:1.5;padding:.5rem .75rem;position:relative}.panel-form-column{flex-direction:column;overflow-x:hidden}.panel-form-column>.panel-form-column,.panel-form-row>.panel-form-column{flex-grow:1;padding:0!important}.panel-form-column>.panel-form-row,.panel-form-row>.panel-form-row{padding:0!important}.panel-form-column>.group{margin-bottom:.25rem;margin-top:.25rem}.avatar-upload{display:flex;flex-direction:column;flex-shrink:0;font-size:4.5rem;height:10.5rem;padding:0;position:relative;width:10rem}.avatar-upload.read-only{height:auto}.avatar-upload .clear-avatar{background-image:radial-gradient(#fff 40%,#0000 75%);font-size:1rem;opacity:0;position:absolute;right:0;top:0}.avatar-upload:hover .clear-avatar{opacity:1}.avatar-upload .avatar-box{height:10rem;position:relative;width:10rem}.avatar-upload .avatar-box>.material-icons{font-size:4rem;line-height:10rem;position:relative;vertical-align:middle}.avatar-upload:after{clear:both;content:".";display:block;height:0;visibility:hidden}.avatar-upload .blank{border:1px dashed #999;color:#999;flex-shrink:0;font-size:1rem;line-height:10rem;text-align:center;vertical-align:middle}.avatar-upload .blank,.avatar-upload img.preview{border-radius:50%;height:10rem;overflow:hidden;width:10rem}.avatar-upload img.preview:before{background:50% no-repeat url(../img/broken_image.png);border-radius:50%;color:#666;content:" ";display:flex;font-size:.9rem;font-weight:lighter;height:10rem;justify-content:center;left:0;position:absolute;top:0;width:10rem}.avatar-upload .inputfile.hidden{height:.1px;opacity:0;overflow:hidden;position:absolute;width:.1px}.avatar-upload .inputfile+label.round{align-items:center;background-color:#fafafa;border-radius:50%;bottom:0;box-shadow:0 1px 4px #0006;cursor:pointer;display:flex;height:3rem;justify-content:center;line-height:3rem;position:absolute;right:0;width:3rem;z-index:1}.avatar-upload .inputfile:focus+label.round{outline:none}.avatar-upload .inputfile+label:hover,.avatar-upload .inputfile:focus+label{background-color:#e3f2fd;color:#42a5f5}#topic-caption-panel{background-color:#b0bec5}#topic-caption-panel a{color:#757575;text-decoration:none}#topic-caption-panel :hover{color:#000}#topic-caption-panel .avatar-box{font-size:1.8rem;height:3rem;margin-right:.35rem;min-width:3rem;position:relative;width:3rem}#topic-caption-panel .avatar-box>.material-icons{font-size:2.4rem;line-height:3rem}#topic-title-group{overflow-x:hidden}#hide-message-view{display:block;margin-right:.35rem}#topic-users{margin-left:auto;margin-right:1rem;width:min-content}#topic-users .avatar-box{display:inline-block;font-size:1rem;height:1.8rem;margin-right:.2rem;min-height:1.8rem;min-width:1.8rem;width:1.8rem}#topic-users .avatar-box>.material-icons{font-size:1.4rem;line-height:1.8rem}#topic-users>span{line-height:2rem;vertical-align:top}#messages-panel{background-color:#eceff1;background-image:url(../img/bg_messages.png);height:100%;overflow-y:scroll;padding:.75rem;position:relative}#messages-container{height:100%;overflow-y:hidden;position:relative}#write-only-background{background-image:repeating-linear-gradient(45deg,#ffffff80,#ffffff80 .5rem,#fffc 0,#fffc 1rem);height:100%;left:0;position:absolute;top:0;width:100%}#write-only-note{height:auto;top:50%;transform:translate(-50%,-50%);width:auto}#peer-messaging-disabled-note,#write-only-note{background-color:#fff;border-radius:.5rem;box-shadow:0 1px .5px #0000001f;color:#666;left:50%;line-height:2rem;padding:.75rem 1.25rem;position:absolute;text-align:center}#peer-messaging-disabled-note{bottom:4.3rem;transform:translate(-50%);width:fit-content}#send-message-panel{align-items:center;background-color:#eceff1;display:flex;flex:none;min-height:4rem;padding:.4rem .4rem .4rem .6rem;z-index:2}#send-message-panel #writing-disabled{font-size:1.2rem;text-align:center;width:100%}#send-message-wrapper{background-color:#eceff1;box-shadow:0 -2px 3px -1px #0000001a;z-index:2}#sendMessage{overflow:hidden;overflow-wrap:break-word}#send-message-panel .material-icons{font-size:1.6rem;min-width:2rem}#send-message-panel .material-icons.secondary,.material-icons.disabled{color:#999!important}#send-message-panel .material-icons.secondary:hover{color:#2196f3!important}#send-message-input{max-height:6rem;min-height:2.5rem;overflow:hidden auto}.accept-invite-panel{background-color:#eceff1;box-shadow:0 -2px 3px -1px #0000001a;width:100%;z-index:1}.accept-invite-panel .title{font-size:1.2rem;padding:.75rem}.accept-invite-panel .footer{background-color:#fafafa;padding-bottom:.35rem;text-align:center;white-space:nowrap}.accept-invite-panel button{border:1px solid #0000;box-shadow:0 1px 2px 0 #00000040;font-size:1rem;height:2em;line-height:2em;margin:.25rem}#dummy-view{align-items:center;background-color:#e0f7fa;display:flex;height:100%;justify-content:center;width:100%}#dummy-view a{display:block;text-align:center;text-decoration:none}#image-preview{background-color:#ffffffe6;display:flex;flex-direction:column;height:100%;left:0;position:absolute;top:0;width:100%;z-index:2}#image-preview-caption-panel{background-color:#eceff1;box-shadow:0 1px 2px silver;display:flex;height:4.6rem;justify-content:space-between;line-height:2.5rem;padding:1rem .75rem 0;z-index:3}#image-preview-caption-panel a{color:#757575;text-decoration:none}#image-preview-caption-panel a:hover{color:#000}#image-preview-container{align-items:center;display:flex;height:100%;justify-content:space-around;overflow:hidden;width:100%}#image-preview-footer{background-color:#eceff1;box-shadow:0 -2px 3px -1px #0000001a;display:flex;height:3.2rem;justify-content:space-around;line-height:1.5rem;z-index:1}#image-preview-container .material-icons{font-size:6rem}#video-container{background-color:#ffffffe6;flex-direction:column;height:100%;justify-content:space-between;left:0;top:0}#video-container,.controls{display:flex;position:absolute;width:100%}.controls{align-items:center;bottom:2.5rem;column-gap:1rem;justify-content:center;z-index:1}.incoming-call .controls{bottom:1rem}.controls button{border-radius:50%;box-shadow:0 3px 6px 0 #00000040;height:4rem;min-width:auto;width:4rem}#video-container-panel{height:100%;position:relative;width:100%}.call-party{background-color:#eee;border:2px solid #ccc;border-radius:.5rem;overflow:hidden}.call-party:hover{border:2px solid #2196f3}.call-party.peer{bottom:1rem;left:1rem;position:absolute;right:1rem;top:1rem;z-index:1}.call-party.self{bottom:.5rem;height:10rem;position:absolute;right:.5rem;width:10rem;z-index:2}.call-party.self[disabled]{display:none}video{height:100%;object-fit:contain;width:100%}.call-party.self video{transform:scaleX(-1)}.call-party[disabled] video{display:none}.caller-card{align-items:center;display:flex;flex-direction:column;height:100%;justify-content:center;left:0;position:absolute;top:0;width:100%}.caller-card .avatar-box{font-size:6rem;height:10rem;width:10rem}.caller-card.pulse .lettertile,.caller-card.pulse img.avatar{animation:active-call 1.5s linear infinite}.caller-card .avatar-box .material-icons{font-size:6rem;line-height:1.6}.call-party .caller-name{background-color:#ffffffb3;border-radius:.35rem;padding:.15rem .5rem;text-shadow:0 0 1px #fff;z-index:1}.call-party.self .caller-name.inactive{bottom:.25rem;position:absolute;right:.25rem}.caller-card .caller-name{font-size:larger;margin-top:.5rem}.caller-card .trusted-badge{display:inline-block}.call-party.peer .caller-name.inactive{bottom:.5rem;font-size:larger;left:1rem;margin:0 auto;position:absolute}.incoming-call{background-color:#fff;border-radius:.3rem;box-shadow:.15rem .15rem 1.5rem #00000073;margin:auto 2rem;max-width:24rem;min-width:16rem;position:relative;width:fit-content}.incoming-call .caller-card{align-items:center;display:flex;flex-direction:column;height:100%;justify-content:center;left:auto;padding:4rem 3.5rem 5.5rem;position:relative;top:auto;width:100%}.incoming-call .caller-name{background-color:#ffffffb3;border-radius:.35rem;padding:.15rem .5rem;text-shadow:0 0 1px #fff;z-index:1}.call-message{display:flex;flex-direction:row}.call-message .duration{font-weight:lighter}@keyframes active-call{0%{box-shadow:0 0 0 .1rem #2196f34d,0 0 0 .3rem #2196f34d,0 0 0 .5rem #2196f34d}to{box-shadow:0 0 0 .4rem #2196f34d,0 0 0 2rem #2196f300,0 0 0 3rem #2196f300}}.chat-box{list-style:none;margin:0 .5rem;padding:0 0 3.5rem;scroll-behavior:smooth}.chat-box.group{margin-left:-.4rem}.chat-box li{align-items:flex-end;display:flex;margin:0;padding:0}.chat-box .right{justify-content:flex-end}.bubble{border-radius:.5rem;color:#212121;display:flex;filter:drop-shadow(.5px .5px .7px rgb(0,0,0,.3));height:auto;margin:0;max-width:36rem;min-width:9rem;padding:.75rem .5rem;position:relative;text-align:left;transition:background-color .5s ease-out;transition-delay:.3s}.chat-box li.single{margin-bottom:.75rem;margin-top:.25rem}.chat-box li.first{margin-bottom:.15rem;margin-top:.25rem}.chat-box li.middle{margin-bottom:.15rem;margin-top:.15rem}.chat-box li.last{margin-bottom:.75rem;margin-top:.15rem}.left .bubble{background-color:#c5e1a5;margin-right:.5rem}.left.flash .bubble{background-color:#94a97c}.left .bubble.tip{border-bottom-left-radius:0}.right .bubble{background-color:#fafafa;margin-left:1.75rem}.right.flash .bubble{background-color:#ccc}.right .bubble.tip{border-bottom-right-radius:0}.chat-box .meta{justify-content:center;margin-bottom:.5rem;margin-top:.5rem}.chat-box .meta .bubble{color:#666;min-width:unset}.meta .bubble.deleted{background-color:#e3f2fd;padding:.75rem .75rem .5rem}.meta .bubble.date{background-color:#fffc;font-size:smaller;padding:.5rem;text-transform:uppercase}.left .bubble.tip:before{background-color:#c5e1a5;border-bottom-left-radius:.3rem;bottom:0;clip-path:polygon(100% 0,0 110%,100% 110%);-webkit-clip-path:polygon(100% 0,0 110%,100% 110%);content:"";height:.85rem;left:-.8rem;position:absolute;transition:background-color .5s ease-out;transition-delay:.3s;width:.85rem}.left.flash .bubble.tip:before{background-color:#94a97c}.right .bubble.tip:before{background-color:#fafafa;border-bottom-right-radius:.3rem;bottom:0;clip-path:polygon(0 0,100% 110%,0 110%);-webkit-clip-path:polygon(0 0,100% 110%,0 110%);content:"";height:.85rem;left:99.8%;position:absolute;transition:background-color .5s ease-out;transition-delay:.3s;width:.85rem}.right.flash .bubble.tip:before{background-color:#ccc}.chat-box .avatar-box{font-size:.8rem;height:1.4rem;margin-bottom:.8rem;margin-right:.8rem;min-height:1.4rem;min-width:1.4rem;position:relative;width:1.4rem}.bubble div.content-meta{width:100%}.bubble div.message-content{margin:0;max-width:36rem;overflow-wrap:anywhere;padding:0 .75rem;position:relative;width:100%}.bubble div.message-content:after{clear:both;content:".";display:block;height:0;visibility:hidden}.chat-box .timestamp-padding{display:inline-block;height:0;width:4rem}.chat-box .timestamp{float:right;position:relative;top:.35rem;user-select:none;white-space:nowrap}.chat-box .author,.chat-box .timestamp{color:#777;font-size:80%}.image-preview,.inline-image{border-radius:.1rem;overflow:hidden;position:relative}.inline-image{max-height:24rem;max-width:36rem}.inline-image>.rounded-container{border-left:.25rem solid #0000;border-right:.25rem solid #0000;bottom:2rem;margin:.25rem auto;position:relative}img.image-preview:before,img.inline-image:before{background:50% no-repeat #ccc url(../img/broken_image.png);color:#666;display:flex;font-size:.9rem;font-weight:lighter;height:100%;justify-content:center;left:0;position:absolute;top:0;width:100%}img.inline-image:before{background-size:3rem 3rem;content:attr(alt)}img.image-preview:before{background-size:10rem 10rem;content:" "}.inline-image.video>img.inline-image:before,img.image-preview.video:before{background:50% no-repeat #ccc url(../img/broken_video.png)}.inline-image.video>img.inline-image:before{background-size:3rem 3rem}.inline-video{align-items:center;display:flex;justify-content:center;position:relative}.inline-video>img.inline-image:before{background:#ccc}.inline-video .duration{background-color:#ffffff80;border-radius:.3rem;bottom:.25rem;color:#333;font-size:80%;left:.25rem;padding:.25rem .5rem;position:absolute}.inline-video .play-control{align-items:center;background-color:#0006;border-radius:50%;cursor:pointer;display:flex;height:4rem;justify-content:center;pointer-events:none;position:absolute;width:4rem}.attachment{display:flex}.attachment:last-of-type{margin-bottom:-.45rem}#info-caption-panel{background-color:#b0bec5}#info-caption-panel a{color:#757575;line-height:1;text-decoration:none}#info-caption-panel :hover{color:#000}#info-title{margin-right:auto}#group-manager{display:flex;flex-direction:column;height:100%;overflow-y:hidden;position:relative}#group-manager-buttons{background-color:#eceff1;border-left:1px solid #ccc;box-shadow:0 -1px #0000001a;display:flex;height:4rem;justify-content:space-around;padding:.4rem;z-index:2}ul.tabbar{background:#eee;display:flex;flex-grow:0;flex-shrink:0;list-style:none;margin:0;overflow:hidden;padding:0 0 0 1rem;width:100%}ul.tabbar>li{box-shadow:inset 0 -2px 2.5px -1px #00000040;height:2.4rem;position:relative}ul.tabbar li.active{background:#fff}ul.tabbar li:after{background:#ccc;bottom:0;content:"";height:.1rem;left:0;position:absolute;width:100%}ul.tabbar li.active:after{animation:tabbar-border-expand .2s cubic-bezier(.4,0,.4,1) 0s alternate forwards;background:#2196f3;bottom:0;content:"";height:.15rem;left:0;position:absolute}@keyframes tabbar-border-expand{0%{opacity:0;width:0}to{opacity:1;width:100%}}ul.tabbar>li>a{color:#2196f399;font-size:1.3rem;font-variant:small-caps;font-weight:400;line-height:2.4rem;overflow:hidden;padding-left:1rem;padding-right:1rem;position:relative;text-align:center;text-decoration:none}ul.tabbar li.active>a{color:#2196f3}.unread{background-color:#0097a7;border-radius:50%;color:#fff;display:inline-block;font-size:.75rem;font-weight:bolder;height:1.35rem;line-height:1.45rem;margin-left:.5rem;text-align:center;vertical-align:middle;width:1.35rem}.material-icons.as-badge{color:#aaa;font-size:1.15rem;padding-left:.2rem}.badge{align-self:flex-start;background-color:#e8e8e8;border:1px solid silver;border-radius:.2rem;color:#666;display:inline-block;font-family:Roboto Mono,Courier,monospace,sans-serif;font-size:.8rem;margin:.05rem .1rem;padding:.05rem .25rem}.badge.green{background-color:#efe;border-color:#aca;color:#383}.badge.yellow{background-color:#ffe;border-color:#cc9;color:#660}.badge.blue{background-color:#eef;border-color:#aad;color:#339}.badge.red{background-color:#fee;border-color:#c99;color:#933}.badge.magenta{background-color:#fef;border-color:#c9c;color:#939}.lettertile{border-radius:50%;padding-bottom:100%;user-select:none;width:100%}.lettertile>div{align-items:center;border-radius:50%;bottom:0;color:#fafafacc;display:flex;flex-grow:0;flex-shrink:0;justify-content:center;left:0;line-height:1;padding-top:.1em;position:absolute;right:0;text-align:center;text-transform:uppercase;top:0}.lettertile:hover{color:#fff}.lettertile.disabled{opacity:.5}.lt-bg-0{background-color:#ef9a9a}.lt-bg-1{background-color:#90caf9}.lt-bg-2{background-color:#b0bec5}.lt-bg-3{background-color:#b39ddb}.lt-bg-4{background-color:#ffab91}.lt-bg-5{background-color:#a5d6a7}.lt-bg-6{background-color:#eee}.lt-bg-7{background-color:#e6ee9c}.lt-bg-8{background-color:#c5e1a5}.lt-bg-9{background-color:#f0e57d}.lt-bg-10{background-color:#f48fb1}.lt-bg-11{background-color:#9fa8da}.lt-bg-12{background-color:#ffe082}.lt-bg-13{background-color:#bcaaa4}.lt-bg-14{background-color:#80deea}.lt-bg-15{background-color:#ce93d8}.dk-bg-0{background-color:#c62828}.dk-bg-1{background-color:#ad1457}.dk-bg-2{background-color:#6a1b9a}.dk-bg-3{background-color:#4527a0}.dk-bg-4{background-color:#283593}.dk-bg-5{background-color:#1565c0}.dk-bg-6{background-color:#0277bd}.dk-bg-7{background-color:#00838f}.dk-bg-8{background-color:#00695c}.dk-bg-9{background-color:#2e7d32}.dk-bg-10{background-color:#558b2f}.dk-bg-11{background-color:#9e9d24}.dk-bg-12{background-color:#f9a825}.dk-bg-13{background-color:#ff8f00}.dk-bg-14{background-color:#ef6c00}.dk-bg-15{background-color:#d84315}.lt-fg-0{color:#ef9a9a!important}.lt-fg-1{color:#90caf9!important}.lt-fg-2{color:#b0bec5!important}.lt-fg-3{color:#b39ddb!important}.lt-fg-4{color:#ffab91!important}.lt-fg-5{color:#a5d6a7!important}.lt-fg-6{color:#eee!important}.lt-fg-7{color:#e6ee9c!important}.lt-fg-8{color:#c5e1a5!important}.lt-fg-9{color:#f0e57d!important}.lt-fg-10{color:#f48fb1!important}.lt-fg-11{color:#9fa8da!important}.lt-fg-12{color:#ffe082!important}.lt-fg-13{color:#bcaaa4!important}.lt-fg-14{color:#80deea!important}.lt-fg-15{color:#ce93d8!important}.dk-fg-0{color:#c62828!important}.dk-fg-1{color:#ad1457!important}.dk-fg-2{color:#6a1b9a!important}.dk-fg-3{color:#4527a0!important}.dk-fg-4{color:#283593!important}.dk-fg-5{color:#1565c0!important}.dk-fg-6{color:#0277bd!important}.dk-fg-7{color:#00838f!important}.dk-fg-8{color:#00695c!important}.dk-fg-9{color:#2e7d32!important}.dk-fg-10{color:#558b2f!important}.dk-fg-11{color:#9e9d24!important}.dk-fg-12{color:#f9a825!important}.dk-fg-13{color:#ff8f00!important}.dk-fg-14{color:#ef6c00!important}.dk-fg-15{color:#d84315!important}.material-icons{font-size:1.4rem;line-height:1;text-align:center;vertical-align:middle}.material-icons.small{font-size:1rem}.material-icons.medium{font-size:1.2rem}.material-icons.big{font-size:2.2rem}.material-icons.bigger{font-size:3rem}.material-icons.huge{font-size:4rem}.composed-material{display:inline-block;position:relative}.composed-material i:nth-child(2){font-size:85%;font-weight:700;left:39%;position:absolute;top:7%}#self-avatar .material-icons{font-size:2.4rem;line-height:3rem}.avatar-box .material-icons{border-radius:50%;color:#fafafacc;height:inherit;width:inherit}.chip-input{align-items:center;background:#0000;border-bottom:1px solid #ccc;box-shadow:0 1px 0 #0000001a;color:#666;cursor:text;display:flex;flex-grow:1;flex-wrap:wrap;font-size:1.1rem;font-weight:400;justify-content:flex-start;margin:.25rem 0;max-height:10rem;min-height:4rem;outline:none;overflow-y:scroll;text-align:center;transition:all .1s ease-in-out}.chip-input.focused{border-bottom:1px solid #2196f3;box-shadow:0 1px 0 #2196f340}.chip-input>input[type=text]{border:none;box-shadow:none;display:inline-block;flex:1 0 auto;min-width:4rem;width:auto}.chip,.chip-input>input[type=text]{height:1.8rem;line-height:1.8;margin:.125rem}.chip{align-items:center;background-color:#eee;border-radius:.9rem;display:flex;flex:0 0 auto;font-size:90%;max-width:12rem;overflow:hidden}.chip,.chip>span{text-overflow:ellipsis;white-space:nowrap}.chip>span{overflow-x:hidden}.chip.invalid{background-color:#fee;color:#c66}.chip>a{background-color:#aaa;border-radius:50%;color:#eee;display:inline-block;height:1.175rem;line-height:1.15;margin:.3rem;min-width:1.175rem;text-decoration:none;width:1.175rem}.chip>a:focus,.chip>a:hover{background-color:#bbb;color:#fff;text-decoration:none}.chip .avatar-box{font-size:1rem;height:1.8rem;margin-right:.2rem;min-height:1.8rem;min-width:1.8rem;position:relative;width:1.8rem}.chip .avatar-box .material-icons{font-size:1.4rem;line-height:1.8rem}.chip .spacer{display:inline-block;height:1.175rem;margin:.3rem;width:.25rem}.load-spinner-box{--size-small:2.5rem;--size-large:4rem;background-color:#fff;border-radius:50%;box-shadow:.1rem .1rem .15rem 1px #00000040;height:var(--size-small);left:0;margin-left:auto;margin-right:auto;padding:.25rem;position:absolute;right:0;top:5rem;width:var(--size-small);z-index:2}.load-spinner-box.large{height:var(--size-large);width:var(--size-large)}.load-spinner-box.clear{background-color:#fff8;-x-box-shadow:none;box-shadow:.1rem .1rem .15rem 1px #0000001f}.load-spinner-box.centered{top:calc(var(--size-small)/2 - .25rem)}.load-spinner-box.large.centered{top:calc(var(--size-large)/2 - .25rem)}.loader-spinner{animation:spin 1.5s linear infinite;border:.35rem solid #f3f3f3;border-radius:50%;border-top-color:#1e88e5;height:2rem;width:2rem}.load-spinner-box.large .loader-spinner{height:3.5rem;width:3.5rem}@keyframes spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.uploader{display:flex}.uploader>div{background-color:#cfd8dc;border-radius:.1rem;height:.6rem;line-height:0;margin:.35rem;padding:.15rem;position:relative;width:6rem}.uploader>div>span{background-color:#1e88e5;border-radius:.08rem;display:inline-block;height:.3rem}.highlight{color:teal;font-weight:bolder}.highlight .preview{color:#5f9ea0;font-weight:inherit}.cropper{align-self:center;height:21rem;margin:1rem auto auto;transform:translateZ(0)}.cropper,.cropper .bounding-box{border-radius:.25rem;position:relative;width:18rem}.cropper .bounding-box{background-color:#999;border:2px solid #1e88e5;box-shadow:1px 1px 3px grey;height:18rem;overflow:hidden;z-index:1}.cropper .preview{max-height:none;max-width:none;position:absolute;z-index:-1}.cropper .cutout{border:1px dashed #999;bottom:0;box-shadow:0 0 150rem 150rem #e6f6ffa8;height:17rem;left:0;margin:auto;position:absolute;right:0;top:0;width:17rem;z-index:0}.cropper .cutout.circle{border-radius:50%}.cropper .overlay{cursor:move;position:absolute;touch-action:none;z-index:1}.cropper .zoom-wrapper{height:2rem;margin:1rem auto;text-align:center;width:80%}.cropper .zoom{box-shadow:none;pointer-events:none;z-index:2}.cropper .zoom:focus{outline:none}.reply-quote{border-left:.25rem solid #039be5;border-radius:.25rem;color:#666;cursor:pointer;font-weight:lighter;line-height:1.5em;padding:.15rem .5rem .25rem;position:relative}.chat-box .bubble .reply-quote{margin:.15rem -.75rem .3rem}.chat-box .bubble .reply-quote:first-child{margin-top:-.25rem}.chat-box .left .reply-quote{background-color:#fff6}.chat-box .right .reply-quote{background-color:#8080801f}.reply-quote .inline-image{margin-bottom:.1rem;vertical-align:middle}.reply-quote img.inline-image:before{content:""}#reply-quote-preview{align-items:center;display:flex}#reply-quote-preview .reply-quote{background-color:#fafafa;cursor:auto;margin:.35rem .5rem 0 0;width:100%}#reply-quote-preview .cancel{min-width:2.4rem;text-align:center}#reply-quote-preview .inline-image{background-color:#ccc}#reply-quote-preview img.inline-image:before{content:""}#send-message-panel #reply-quote-preview{width:100%}#send-message-panel #reply-quote-preview .reply-quote{margin-bottom:.35rem}.forwarding-quote{font-size:200%;line-height:200%}.mention{font-weight:500}.forward-dialog{background-color:#fff;border-radius:.3rem;box-shadow:.15rem .15rem 1.5rem #00000073;height:80%;margin:auto 1rem;overflow:hidden;padding:.5rem;position:relative;width:24rem}.forward-dialog .scrollable-panel{height:80%}.audio{align-items:center;background-color:#eee;border-radius:1.5rem;display:flex;flex:none;height:3rem;margin-left:auto}.audio canvas{height:2.6rem;margin-right:2rem;width:14rem}.audio canvas.playback{margin-right:0}.audio .duration{font-size:large}.audio-player{align-items:center;display:flex}.audio-player .material-icons.large{color:#667575cc;font-size:2.4rem}.audio-player .material-icons.disabled{color:#999c;cursor:default}.audio-player .playback{height:2.6rem;width:14rem}.audio-player canvas.playback{display:block}.audio-player div.playback{align-items:center;color:#757575cc;display:flex;font-size:small;justify-content:center}.audio-player .timer{color:#666c;font-size:smaller}#pinned-wrapper{margin-left:auto;margin-right:1rem}#pinned-wrapper,.pinned{align-items:center;display:flex;height:100%;position:relative}.pinned{background-color:#fafafa;background-position:50%;border-radius:0 .25rem .25rem 0;color:#666;cursor:pointer;font-weight:lighter;line-height:1.5em;min-width:24rem;overflow-x:hidden;padding:.15rem .5rem .25rem;text-overflow:ellipsis;transition:background .4s;width:100%}.pinned:hover{background-color:#fafdff}.pinned:active{background-color:#d8e8ff;transition:background 0s}.pinned-scroll{align-items:center;background-color:#eeee;border-radius:.25rem 0 0 .25rem;display:flex;flex-direction:column;height:100%;justify-content:space-evenly;margin-left:.35rem;padding:.1rem;position:relative}.pinned-scroll .dot{background-color:#999;border-radius:50%;height:.3rem;width:.3rem}.pinned-scroll .adot{background-color:#039be5;border-radius:50%;height:.45rem;width:.45rem}#pinned-wrapper .menuTrigger.upper{top:.25rem}#pinned-wrapper .menuTrigger.lower{bottom:.25rem}#pinned-wrapper:hover .menuTrigger{opacity:.9}#pinned-wrapper:hover .menuTrigger a{color:#757575}.drag-n-drop{align-items:center;background-color:#fffffff2;border:.15rem dashed grey;border-radius:1rem;bottom:1.5rem;color:grey;display:flex;font-size:2rem;justify-content:center;left:1.5rem;outline:.5rem solid #fffffff2;position:absolute;right:1.5rem;top:1.5rem;z-index:3}.country-flag{display:inline-block;font-size:larger}.dial-code{cursor:pointer;display:inline-block;margin-bottom:.15rem;vertical-align:middle;white-space:nowrap}ul.phone-country-selector{list-style:none;overflow-x:hidden}ul.phone-country-selector>li{cursor:pointer;font-weight:lighter;padding:.25rem .5rem .15rem;position:relative;width:100%}ul.phone-country-selector>li:hover{background-color:#eceff1}ul.phone-country-selector>li.selected{background-color:#cfd8dc}ul.phone-country-selector .dial-code{color:#1e88e5;font-weight:400;position:absolute;right:.5rem}ul.phone-country-selector span{display:inline-block}ul.phone-country-selector span.country{overflow-x:hidden;text-overflow:ellipsis}@media (min-width:1440px){#app-container{max-width:114rem}}@media (max-width:960px){#mountPoint{padding:0}.pinned{min-width:16rem}}@media (max-width:640px){#app-container{border-radius:0;box-shadow:none;width:100%}#info-view,#sidepanel{width:100%}.forward-dialog{border-radius:.3rem .3rem 0 0;margin:auto 0 0;width:100%}.menuTrigger{opacity:.3}#send-message-input{transition-property:-tinode-mobile}#pinned-wrapper{height:3.5rem;margin:.25rem}.pinned{min-width:unset}} \ No newline at end of file +*{box-sizing:border-box;font-family:Roboto,Arial,sans-serif;margin:0;padding:0;scrollbar-color:#0000004d #ffffff1a;scrollbar-width:thin;text-rendering:optimizeLegibility}body,html{background-color:silver;box-shadow:inset 0 10rem #3949ab;color:#666;font-size:10pt;height:100%;overflow:hidden;width:100%}tt{font-family:Roboto Mono,Courier,monospace}a{color:#2196f3;text-decoration:none}a:focus,a:hover{color:#0a6ebd;text-decoration:underline}a.danger{color:#d32f2f}a.danger:focus,a.danger:hover{color:#f44336}a.gray:focus,a.gray:hover{color:#999}form{line-height:1.5;padding:.5rem .75rem}form,label{font-size:1.1rem}label{margin-right:auto}label.small{color:#1e88e5;font-size:.95rem}label.large{color:#1e88e5;font-size:1.1rem}img.avatar{border-radius:50%;height:100%;width:100%}button{border:1px solid #0000;border-radius:4px;box-shadow:0 1px 3px 0 #00000040;cursor:pointer;display:inline-block;font-family:inherit;font-size:1.05rem;font-weight:400;height:2.2rem;line-height:2.2rem;margin:0 .35rem;min-width:5rem;padding-left:1.2rem;padding-right:1.2rem;text-align:center;text-transform:uppercase;touch-action:manipulation;vertical-align:middle;white-space:nowrap}button[disabled],html input[disabled]{box-shadow:none;cursor:default;filter:grayscale(50%);opacity:.65}button.round{border-radius:50%;box-shadow:0 2px .5rem 0 #00000040;height:3rem;line-height:3.5rem;margin:0;outline:none;padding:0;width:3rem;z-index:2}button.round.small{box-shadow:0 2px .35rem 0 #00000040;height:2rem;line-height:2rem;width:2rem}button:active:not([disabled]),button:hover:not([disabled]){color:#fff}button:active{box-shadow:inset 0 3px .5rem rgba(0,0,0,.125)}button:active.round.small{box-shadow:inset 0 2px .35rem rgba(0,0,0,.125)}button.primary{background-color:#1e88e5;color:#fff}button.primary:active:not([disabled]),button.primary:hover:not([disabled]){background-color:#2962ff}button.secondary{background-color:#fff;color:#2196f3}button.secondary:active:not([disabled]),button.secondary:hover:not([disabled]){background-color:#e3f2fd}button.outline{background-color:initial;border:1px solid silver;box-shadow:none;color:#2196f3}button.outline:active:not([disabled]),button.outline:hover:not([disabled]){background-color:#e8eaf6}button.danger{background-color:#ec6560;color:#fff}button.danger:active:not([disabled]),button.danger:hover:not([disabled]){background-color:#f77}button.positive{background-color:#71c46f;color:#fff}button.positive:active:not([disabled]),button.positive:hover:not([disabled]){background-color:#7fed7f}input,textarea{background:#0000;border:none;color:#666;font-family:inherit;font-size:1.1rem;margin:.25rem 0;outline:none;padding:0 .125rem}input[type=email],input[type=password],input[type=search],input[type=tel],input[type=text],textarea{border-bottom:1px solid #ccc;box-shadow:0 1px 0 #0000001a;height:2.5rem;transition:all .1s ease-in-out,height 0s}input[type=email],input[type=password],input[type=tel],input[type=text],textarea{width:100%}input[type=email]:focus,input[type=password]:focus,input[type=search]:focus,input[type=tel]:focus,input[type=text]:focus,textarea:focus{border-bottom:1px solid #2196f3;box-shadow:0 1px 0 #2196f340}input[type=email].invalid,input[type=password].invalid,input[type=search].invalid,input[type=tel].invalid,input[type=text].invalid,textarea.invalid{border-bottom:1px solid #e57373;box-shadow:0 1px 0 #e5737340}input[type=email]::placeholder,input[type=password]::placeholder,input[type=search]::placeholder,input[type=tel]::placeholder,input[type=text]::placeholder,textarea::placeholder{color:#bbb;font-weight:lighter}input[type=password].with-visibility,input[type=text].with-visibility{margin-right:-2rem;padding-right:2rem}textarea{padding-top:.45rem;resize:none}textarea.inplace-edit{font-size:unset;height:unset}::-webkit-scrollbar{width:.6rem}::-webkit-scrollbar-track{background-color:#ffffff1a;-webkit-box-shadow:inset 0 0 6px #0003;box-shadow:inset 0 0 6px #0003}::-webkit-scrollbar-thumb{background-color:#0000004d}ul.menu{background-color:#fff;border-radius:.2rem;box-shadow:0 1px 6px #00000073;list-style:none;padding-bottom:.35rem;padding-top:.35rem;position:absolute;width:12rem;z-index:4}ul.menu>li{cursor:pointer;padding:.75rem .75rem .75rem 1.25rem}ul.menu>li:hover{background-color:#f5f5f5}ul.menu>li.separator{height:1px;margin:2px;padding:0}ul.menu>li.separator,ul.menu>li.separator:hover{background-color:#ccc}.menuTrigger{background-color:inherit;border-radius:.7rem;height:1.4rem;line-height:1.4rem;opacity:0;position:absolute;right:.25rem;text-align:center;width:1.4rem}.menuTrigger a{color:#757575}li .menuTrigger{top:.25rem}li:hover .menuTrigger{opacity:.9}li:hover .menuTrigger a{color:#757575}div.alert-container{align-items:center;background:#f0f0f0d9;display:flex;height:100%;justify-content:center;overflow:hidden;padding:1rem;position:absolute;width:100%;z-index:3}div.alert{background-color:#fff;border-radius:.3rem;box-shadow:.15rem .15rem 1.5rem #00000073;height:min-content;margin:auto 2rem;max-height:40rem;max-width:24rem;min-width:16rem;overflow:hidden;padding:1rem;position:relative;width:fit-content}div.alert-container .title{color:#2196f3;font-size:1.2rem;font-weight:500;padding:0 0 .35rem;position:relative;width:100%}div.alert-container .title.with-control{align-items:center;display:flex;flex:none;justify-content:space-between;padding:.5rem .5rem 0;position:relative}div.alert-container .content{padding:.5rem 0;position:relative}div.trusted-badge{margin:.25rem 0}.blue{color:#2196f3!important}.lt-blue{color:#64b5f6!important}.verified-color{color:#03a9f4!important}.staff-color{color:#689f38!important}.danger-color{color:#ffc107!important}.green{color:#388e3c}.white{color:#fff!important}.red{color:#d32f2f!important}.badge-inv{color:#fffd!important}.gray{color:#757575!important}.light-gray{color:#bbb!important}.large{font-size:120%}.small{font-size:90%}.float-right{position:absolute;right:.5rem}.hr{background-color:#f0f0f0;box-shadow:inset 0 .25rem .25rem -.25rem #00000026,inset 0 -.25rem .25rem -.25rem #00000026;display:block;height:.45rem;min-height:.3rem;width:100%}.hr.thin{height:.015rem}.ellipsized{overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.flat-button{align-items:center;background-color:#fff;display:flex;font-weight:400;height:2em;line-height:2em;margin:.15rem .35rem;text-align:center;text-transform:uppercase;touch-action:manipulation;vertical-align:middle;white-space:nowrap;z-index:1}.flat-button:focus,.flat-button:hover{text-decoration:none}.flat-button.faux{background-color:#eee;border:1px solid #999;border-radius:3px;display:inline-block;height:1.4em;line-height:1.4em;margin:.15rem;padding:0 .35rem;text-transform:none}.action-button{background-color:#fafafa;border-radius:50%;bottom:1rem;box-shadow:0 2px .5rem 0 #00000040;color:#999;display:block;font-size:1.8rem;height:3.25rem;margin:0;min-height:unset;min-width:unset;outline:none;padding:0;position:absolute;right:1rem;transition:all .15s;width:3.25rem;z-index:2}.action-button:focus,.action-button:hover{background-color:#f0f0f0;color:#888}.action-button:active{background-color:#eee;color:#777}.action-button.hidden{bottom:2.625rem;font-size:1px;height:1px;line-height:1px;opacity:0;right:2.625rem;width:1px}.group-focus{outline:none}#mountPoint{height:100%;padding-bottom:1rem;padding-top:1rem}#noscript-message{background-color:#fff;border-radius:.25rem;box-shadow:1px 2px .3rem gray;display:flex;flex-direction:column;margin-left:auto;margin-right:auto;margin-top:5rem;max-width:30rem;overflow:hidden;position:relative}#noscript-title{background-color:#2196f3;color:#bbdefb;font-size:120%;font-weight:bolder;padding:1rem}#noscript-content{padding:1rem}#app-container{background-color:#fff;border-radius:.25rem;box-shadow:1px 2px .3rem gray;display:flex;height:100%;margin-left:auto;margin-right:auto;max-width:84rem;overflow:hidden;position:relative}#sidepanel{flex-grow:0;flex-shrink:0.3;min-width:18rem;width:24rem}#sidepanel,#topic-view{display:flex;flex-direction:column;height:100%;position:relative}#topic-view{overflow-x:hidden;width:100%}#info-view{display:flex;flex-direction:column;flex-grow:0;flex-shrink:0.3;height:100%;min-width:18rem;width:24rem}.center-medium-text{align-items:center;display:flex;font-size:1.4rem;height:100%;justify-content:center;text-align:center;width:100%}.nodisplay{display:none!important}.quoted{margin-left:1rem}.space-right{margin-right:.25rem}.rounded-container{background-color:#fafafa;border-radius:.1rem;margin:.25rem;padding:.25rem;position:relative}.in-place-edit{border-bottom:1px dashed #ddd;cursor:pointer;display:inline-block;font-family:inherit;font-size:1rem;margin:.25rem .125rem 0;vertical-align:initial;width:100%}.in-place-edit.short{font-size:1.1rem;height:2.5rem;line-height:2.25}.in-place-edit.disabled{border-bottom:none;color:#888;cursor:default}.in-place-edit.placeholder{color:#bbb}.in-place-edit span{display:inline-block}.in-place-edit.short span{display:block;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}table.permission-editor{width:100%}table.permission-editor td{font-size:1.1rem;margin:.35rem 0;vertical-align:middle}table.permission-editor td.checkbox{color:#999;text-align:center}.permission-editor .material-icons{font-size:1.3rem;line-height:1.3rem}.material-icons.clickable{border-bottom:none;cursor:pointer}.clickable{border-bottom:1px dashed #ddd}.clean-clickable,.clickable,.image-clickable{cursor:pointer}.panel-title{font-size:1.4rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.panel-title.deleted{text-decoration:line-through}.caption-panel{box-shadow:0 1px 2px gray;flex:none;height:4rem;overflow-x:hidden;white-space:nowrap;z-index:1}.caption-panel,.dialog-buttons{align-items:center;display:flex;padding:.5rem}.dialog-buttons{justify-content:flex-end}.dialog-buttons button{margin:0 .5rem}.avatar-box{flex-grow:0;flex-shrink:0;position:relative}.bot-form{display:flex;flex-direction:column;line-height:2rem;min-width:8rem;overflow:hidden}.bot-form div{min-height:2rem;vertical-align:middle}.bot-form button{background-color:#eef;color:#2196f3;display:inline-block;font-size:inherit;height:2rem;line-height:2rem;margin:.15rem;text-transform:none}.bot-form>div>button{width:auto}.bot-form button:active,.bot-form button:focus,.bot-form button:hover{background-color:#e3f2fd;outline:0}#side-caption-panel{background-color:#2196f3;color:#bbdefb}#side-caption-panel a{color:#bbdefb;line-height:1;padding-left:.5rem}#side-caption-panel :hover{color:#fff}#sidepanel-title{margin-left:.5rem;margin-right:auto}#self-avatar{border-radius:50%;flex:none;height:3rem;min-width:3rem;width:3rem}#self-avatar.avatar-box{font-size:1.8rem}#settings-form ul{list-style:none}#settings-form li{vertical-align:middle}#settings-form label{display:inline-block;padding-left:.5rem}input#host-name{width:100%}input.search{text-indent:1.4rem}i.search{left:.6rem;position:absolute}.info-box{display:none;overflow:hidden;padding:1rem 1.5rem .75rem .5rem;position:relative}.info-box>span{line-height:1.35rem}.info-box .cancel{position:absolute;right:.25rem;top:.5rem}.info-box.error{background-color:#ffcdd2;border-bottom:1px solid #ffbfc8;color:#b71c1c;display:flex}.info-box.warning{background-color:#fff9c4;border-bottom:1px solid #fff59d;color:#6d4c41;display:flex}.info-box.info{background-color:#e1f5fe;border-bottom:1px solid #b3e5fc;color:#0288d1;display:flex}.info-box .cancel .material-icons{color:#757575;font-size:1rem}.info-box.error .cancel .material-icons{color:#b71c1c}.info-box .icon{display:block;margin-right:.5rem}.info-box .icon .material-icons{font-size:1.5rem}.info-box.warning .icon .material-icons{color:#fbc02d}.info-box.error .icon .material-icons{color:#ef5350}.info-box.info .icon .material-icons{color:#0288d1}.flex-column{display:flex;flex-direction:column;height:100%;overflow-x:hidden}.flex-column.narrow{height:auto}.scrollable-panel{height:100%;margin-bottom:auto;margin-top:.25rem;overflow-x:hidden;overflow-y:auto;scroll-behavior:smooth}.contact-box{list-style:none;overflow-x:hidden}.contact-box>li{background:linear-gradient(90deg,#0000 3.5rem,#eee 1px,#eee) 0 100% /100% 1px no-repeat,#fff;cursor:pointer;display:flex;flex-grow:0;flex-shrink:0;min-height:3.75rem;overflow-x:hidden;padding:.35rem .25rem .5rem .35rem;position:relative}.contact-box.small>li{min-height:2.5rem;padding:.25rem .25rem .35rem .35rem}.contact-box>li:last-child{background:#fff}.contact-box>li:hover{background-color:#eceff1}.contact-box>li.selected{background-color:#cfd8dc}.contact-box>li.action{border-bottom:none;min-height:2.5rem}.contact-box .text-box{overflow-x:hidden}.contact-box .contact-title{font-size:1.05rem;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.contact-box .contact-title.deleted{opacity:.66;text-decoration:line-through;text-decoration-thickness:.5px}.contact-box .contact-comment{font-weight:lighter}.contact-box .contact-comment,.contact-box .contact-comment>span{overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.contact-box .contact-comment b{font-weight:bolder}.contact-box .contact-comment .material-icons{color:#777;margin-bottom:.2rem}.contact-box .avatar-box{font-size:1.8rem;height:3rem;margin-right:.35rem;min-height:3rem;min-width:3rem;overflow:hidden;padding:0;position:relative;width:3rem}.contact-box .avatar{border-radius:50%;height:3rem;width:3rem}.contact-box.small .avatar-box{font-size:1.2rem;height:2rem;min-height:2rem;min-width:2rem;width:2rem}.contact-box.small .avatar{height:2rem;width:2rem}.avatar.deleted{filter:grayscale(1);opacity:.75}.contact-box .avatar-box>.material-icons{display:flex;flex-direction:column;font-size:2.4rem;justify-content:space-around;line-height:3rem}.contact-box.small .avatar-box>.material-icons{font-size:1.6rem;line-height:2rem}.contact-box .text-box{display:flex;flex-direction:column;justify-content:space-around}.contact-box .text-box>div{align-items:center;display:flex;flex-direction:row}.contact-box .action-text{cursor:pointer;font-size:.95rem;line-height:2.5rem;margin:0 auto;text-align:center}img.channel{height:1.25rem;margin-left:.3rem;vertical-align:middle;width:1.25rem}.large img.channel{height:1.45rem;margin-bottom:.15rem;margin-left:.5rem;width:1.45rem}.avatar-box .online,.offline{border-radius:50%;bottom:.1rem;flex-shrink:0;height:.75rem;min-height:.75rem;min-width:.75rem;position:absolute;right:0;width:.75rem}.avatar-box .online{background-color:#4caf50}.avatar-box .offline{background-color:silver}.online.typing{animation:typing .5s infinite}@keyframes typing{0%,to{transform:translateX(0)}50%{transform:translateX(-.3rem)}}.contact-box .checkmark.material-icons{border:0 solid #0000;color:#0097a7;overflow:visible;padding-left:.5px}.contact-box .checkmark.material-icons,.contact-box .deleted.material-icons{background-color:#fff;bottom:0;font-size:1.5rem;height:1.5rem;position:absolute;right:0;width:1.5rem}.contact-box .deleted.material-icons{color:#999}#add-topic{bottom:1rem;position:absolute;right:1rem}.panel-form{display:flex;flex-direction:column;padding:0;position:relative}.panel-form-row{align-items:center;flex-shrink:0}.panel-form-column,.panel-form-row{display:flex;flex-grow:0;line-height:1.5;padding:.5rem .75rem;position:relative}.panel-form-column{flex-direction:column;overflow-x:hidden}.panel-form-column>.panel-form-column,.panel-form-row>.panel-form-column{flex-grow:1;padding:0!important}.panel-form-column>.panel-form-row,.panel-form-row>.panel-form-row{padding:0!important}.panel-form-column>.group{margin-bottom:.25rem;margin-top:.25rem}.avatar-upload{display:flex;flex-direction:column;flex-shrink:0;font-size:4.5rem;height:10.5rem;padding:0;position:relative;width:10rem}.avatar-upload.read-only{height:auto}.avatar-upload .clear-avatar{background-image:radial-gradient(#fff 40%,#0000 75%);font-size:1rem;opacity:0;position:absolute;right:0;top:0}.avatar-upload:hover .clear-avatar{opacity:1}.avatar-upload .avatar-box{height:10rem;position:relative;width:10rem}.avatar-upload .avatar-box>.material-icons{font-size:4rem;line-height:10rem;position:relative;vertical-align:middle}.avatar-upload:after{clear:both;content:".";display:block;height:0;visibility:hidden}.avatar-upload .blank{border:1px dashed #999;color:#999;flex-shrink:0;font-size:1rem;line-height:10rem;text-align:center;vertical-align:middle}.avatar-upload .blank,.avatar-upload img.preview{border-radius:50%;height:10rem;overflow:hidden;width:10rem}.avatar-upload img.preview:before{background:50% no-repeat url(../img/broken_image.png);border-radius:50%;color:#666;content:" ";display:flex;font-size:.9rem;font-weight:lighter;height:10rem;justify-content:center;left:0;position:absolute;top:0;width:10rem}.avatar-upload .inputfile.hidden{height:.1px;opacity:0;overflow:hidden;position:absolute;width:.1px}.avatar-upload .inputfile+label.round{align-items:center;background-color:#fafafa;border-radius:50%;bottom:0;box-shadow:0 1px 4px #0006;cursor:pointer;display:flex;height:3rem;justify-content:center;line-height:3rem;position:absolute;right:0;width:3rem;z-index:1}.avatar-upload .inputfile:focus+label.round{outline:none}.avatar-upload .inputfile+label:hover,.avatar-upload .inputfile:focus+label{background-color:#e3f2fd;color:#42a5f5}#topic-caption-panel{background-color:#b0bec5}#topic-caption-panel a{color:#757575;text-decoration:none}#topic-caption-panel :hover{color:#000}#topic-caption-panel .avatar-box{font-size:1.8rem;height:3rem;margin-right:.35rem;min-width:3rem;position:relative;width:3rem}#topic-caption-panel .avatar-box>.material-icons{font-size:2.4rem;line-height:3rem}#topic-title-group{overflow-x:hidden}#hide-message-view{display:block;margin-right:.35rem}#topic-users{margin-left:auto;margin-right:1rem;width:min-content}#topic-users .avatar-box{display:inline-block;font-size:1rem;height:1.8rem;margin-right:.2rem;min-height:1.8rem;min-width:1.8rem;width:1.8rem}#topic-users .avatar-box>.material-icons{font-size:1.4rem;line-height:1.8rem}#topic-users>span{line-height:2rem;vertical-align:top}#messages-panel{background-color:#eceff1;background-image:url(../img/bg_messages.png);height:100%;overflow-y:scroll;padding:.75rem;position:relative}#messages-container{height:100%;overflow-y:hidden;position:relative}#write-only-background{background-image:repeating-linear-gradient(45deg,#ffffff80,#ffffff80 .5rem,#fffc 0,#fffc 1rem);height:100%;left:0;position:absolute;top:0;width:100%}#write-only-note{height:auto;top:50%;transform:translate(-50%,-50%);width:auto}#peer-messaging-disabled-note,#write-only-note{background-color:#fff;border-radius:.5rem;box-shadow:0 1px .5px #0000001f;color:#666;left:50%;line-height:2rem;padding:.75rem 1.25rem;position:absolute;text-align:center}#peer-messaging-disabled-note{bottom:4.3rem;transform:translate(-50%);width:fit-content}#send-message-panel{align-items:center;background-color:#eceff1;display:flex;flex:none;min-height:4rem;padding:.4rem .4rem .4rem .6rem;z-index:2}#send-message-panel #writing-disabled{font-size:1.2rem;text-align:center;width:100%}#send-message-wrapper{background-color:#eceff1;box-shadow:0 -2px 3px -1px #0000001a;z-index:2}#sendMessage{overflow:hidden;overflow-wrap:break-word}#send-message-panel .material-icons{font-size:1.6rem;min-width:2rem}#send-message-panel .material-icons.secondary,.material-icons.disabled{color:#999!important}#send-message-panel .material-icons.secondary:hover{color:#2196f3!important}#send-message-input{max-height:6rem;min-height:2.5rem;overflow:hidden auto}.accept-invite-panel{background-color:#eceff1;box-shadow:0 -2px 3px -1px #0000001a;width:100%;z-index:1}.accept-invite-panel .title{font-size:1.2rem;padding:.75rem}.accept-invite-panel .footer{background-color:#fafafa;padding-bottom:.35rem;text-align:center;white-space:nowrap}.accept-invite-panel button{border:1px solid #0000;box-shadow:0 1px 2px 0 #00000040;font-size:1rem;height:2em;line-height:2em;margin:.25rem}#dummy-view{align-items:center;background-color:#e0f7fa;display:flex;height:100%;justify-content:center;width:100%}#dummy-view a{display:block;text-align:center;text-decoration:none}#image-preview{background-color:#ffffffe6;display:flex;flex-direction:column;height:100%;left:0;position:absolute;top:0;width:100%;z-index:2}#image-preview-caption-panel{background-color:#eceff1;box-shadow:0 1px 2px silver;display:flex;height:4.6rem;justify-content:space-between;line-height:2.5rem;padding:1rem .75rem 0;z-index:3}#image-preview-caption-panel a{color:#757575;text-decoration:none}#image-preview-caption-panel a:hover{color:#000}#image-preview-container{align-items:center;display:flex;height:100%;justify-content:space-around;overflow:hidden;width:100%}#image-preview-footer{background-color:#eceff1;box-shadow:0 -2px 3px -1px #0000001a;display:flex;height:3.2rem;justify-content:space-around;line-height:1.5rem;z-index:1}#image-preview-container .material-icons{font-size:6rem}#video-container{background-color:#ffffffe6;flex-direction:column;height:100%;justify-content:space-between;left:0;top:0}#video-container,.controls{display:flex;position:absolute;width:100%}.controls{align-items:center;bottom:2.5rem;column-gap:1rem;justify-content:center;z-index:1}.incoming-call .controls{bottom:1rem}.controls button{border-radius:50%;box-shadow:0 3px 6px 0 #00000040;height:4rem;min-width:auto;width:4rem}#video-container-panel{height:100%;position:relative;width:100%}.call-party{background-color:#eee;border:2px solid #ccc;border-radius:.5rem;overflow:hidden}.call-party:hover{border:2px solid #2196f3}.call-party.peer{bottom:1rem;left:1rem;position:absolute;right:1rem;top:1rem;z-index:1}.call-party.self{bottom:.5rem;height:10rem;position:absolute;right:.5rem;width:10rem;z-index:2}.call-party.self[disabled]{display:none}video{height:100%;object-fit:contain;width:100%}.call-party.self video{transform:scaleX(-1)}.call-party[disabled] video{display:none}.caller-card{align-items:center;display:flex;flex-direction:column;height:100%;justify-content:center;left:0;position:absolute;top:0;width:100%}.caller-card .avatar-box{font-size:6rem;height:10rem;width:10rem}.caller-card.pulse .lettertile,.caller-card.pulse img.avatar{animation:active-call 1.5s linear infinite}.caller-card .avatar-box .material-icons{font-size:6rem;line-height:1.6}.call-party .caller-name{background-color:#ffffffb3;border-radius:.35rem;padding:.15rem .5rem;text-shadow:0 0 1px #fff;z-index:1}.call-party.self .caller-name.inactive{bottom:.25rem;position:absolute;right:.25rem}.caller-card .caller-name{font-size:larger;margin-top:.5rem}.caller-card .trusted-badge{display:inline-block}.call-party.peer .caller-name.inactive{bottom:.5rem;font-size:larger;left:1rem;margin:0 auto;position:absolute}.incoming-call{background-color:#fff;border-radius:.3rem;box-shadow:.15rem .15rem 1.5rem #00000073;margin:auto 2rem;max-width:24rem;min-width:16rem;position:relative;width:fit-content}.incoming-call .caller-card{align-items:center;display:flex;flex-direction:column;height:100%;justify-content:center;left:auto;padding:4rem 3.5rem 5.5rem;position:relative;top:auto;width:100%}.incoming-call .caller-name{background-color:#ffffffb3;border-radius:.35rem;padding:.15rem .5rem;text-shadow:0 0 1px #fff;z-index:1}.call-message{display:flex;flex-direction:row}.call-message .duration{font-weight:lighter}@keyframes active-call{0%{box-shadow:0 0 0 .1rem #2196f34d,0 0 0 .3rem #2196f34d,0 0 0 .5rem #2196f34d}to{box-shadow:0 0 0 .4rem #2196f34d,0 0 0 2rem #2196f300,0 0 0 3rem #2196f300}}.chat-box{list-style:none;margin:0 .5rem;padding:0 0 3.5rem;scroll-behavior:smooth}.chat-box.group{margin-left:-.4rem}.chat-box li{align-items:flex-end;display:flex;margin:0;padding:0}.chat-box .right{justify-content:flex-end}.bubble{border-radius:.5rem;color:#212121;display:flex;filter:drop-shadow(.5px .5px .7px rgb(0,0,0,.3));height:auto;margin:0;max-width:36rem;min-width:9rem;padding:.75rem .5rem;position:relative;text-align:left;transition:background-color .5s ease-out;transition-delay:.3s}.chat-box li.single{margin-bottom:.75rem;margin-top:.25rem}.chat-box li.first{margin-bottom:.15rem;margin-top:.25rem}.chat-box li.middle{margin-bottom:.15rem;margin-top:.15rem}.chat-box li.last{margin-bottom:.75rem;margin-top:.15rem}.left .bubble{background-color:#c5e1a5;margin-right:.5rem}.left.flash .bubble{background-color:#94a97c}.left .bubble.tip{border-bottom-left-radius:0}.right .bubble{background-color:#fafafa;margin-left:1.75rem}.right.flash .bubble{background-color:#ccc}.right .bubble.tip{border-bottom-right-radius:0}.chat-box .meta{justify-content:center;margin-bottom:.5rem;margin-top:.5rem}.chat-box .meta .bubble{color:#666;min-width:unset}.meta .bubble.deleted{background-color:#e3f2fd;padding:.75rem .75rem .5rem}.meta .bubble.date{background-color:#fffc;font-size:smaller;padding:.5rem;text-transform:uppercase}.left .bubble.tip:before{background-color:#c5e1a5;border-bottom-left-radius:.3rem;bottom:0;clip-path:polygon(100% 0,0 110%,100% 110%);-webkit-clip-path:polygon(100% 0,0 110%,100% 110%);content:"";height:.85rem;left:-.8rem;position:absolute;transition:background-color .5s ease-out;transition-delay:.3s;width:.85rem}.left.flash .bubble.tip:before{background-color:#94a97c}.right .bubble.tip:before{background-color:#fafafa;border-bottom-right-radius:.3rem;bottom:0;clip-path:polygon(0 0,100% 110%,0 110%);-webkit-clip-path:polygon(0 0,100% 110%,0 110%);content:"";height:.85rem;left:99.8%;position:absolute;transition:background-color .5s ease-out;transition-delay:.3s;width:.85rem}.right.flash .bubble.tip:before{background-color:#ccc}.chat-box .avatar-box{font-size:.8rem;height:1.4rem;margin-bottom:.8rem;margin-right:.8rem;min-height:1.4rem;min-width:1.4rem;position:relative;width:1.4rem}.bubble div.content-meta{width:100%}.bubble div.message-content{margin:0;max-width:36rem;overflow-wrap:anywhere;padding:0 .75rem;position:relative;width:100%}.bubble div.message-content:after{clear:both;content:".";display:block;height:0;visibility:hidden}.chat-box .timestamp-padding{display:inline-block;height:0;width:4rem}.chat-box .timestamp{float:right;position:relative;top:.35rem;user-select:none;white-space:nowrap}.chat-box .author,.chat-box .timestamp{color:#777;font-size:80%}.image-preview,.inline-image{border-radius:.1rem;overflow:hidden;position:relative}.inline-image{max-height:24rem;max-width:36rem}.inline-image>.rounded-container{border-left:.25rem solid #0000;border-right:.25rem solid #0000;bottom:2rem;margin:.25rem auto;position:relative}img.image-preview:before,img.inline-image:before{background:50% no-repeat #ccc url(../img/broken_image.png);color:#666;display:flex;font-size:.9rem;font-weight:lighter;height:100%;justify-content:center;left:0;position:absolute;top:0;width:100%}img.inline-image:before{background-size:3rem 3rem;content:attr(alt)}img.image-preview:before{background-size:10rem 10rem;content:" "}.inline-image.video>img.inline-image:before,img.image-preview.video:before{background:50% no-repeat #ccc url(../img/broken_video.png)}.inline-image.video>img.inline-image:before{background-size:3rem 3rem}.inline-video{align-items:center;display:flex;justify-content:center;position:relative}.inline-video>img.inline-image:before{background:#ccc}.inline-video .duration{background-color:#ffffff80;border-radius:.3rem;bottom:.25rem;color:#333;font-size:80%;left:.25rem;padding:.25rem .5rem;position:absolute}.inline-video .play-control{align-items:center;background-color:#0006;border-radius:50%;cursor:pointer;display:flex;height:4rem;justify-content:center;pointer-events:none;position:absolute;width:4rem}.attachment{display:flex}.attachment:last-of-type{margin-bottom:-.45rem}#info-caption-panel{background-color:#b0bec5}#info-caption-panel a{color:#757575;line-height:1;text-decoration:none}#info-caption-panel :hover{color:#000}#info-title{margin-right:auto}#group-manager{display:flex;flex-direction:column;height:100%;overflow-y:hidden;position:relative}#group-manager-buttons{background-color:#eceff1;border-left:1px solid #ccc;box-shadow:0 -1px #0000001a;display:flex;height:4rem;justify-content:space-around;padding:.4rem;z-index:2}ul.tabbar{background:#eee;display:flex;flex-grow:0;flex-shrink:0;list-style:none;margin:0;overflow:hidden;padding:0 0 0 1rem;width:100%}ul.tabbar>li{box-shadow:inset 0 -2px 2.5px -1px #00000040;height:2.4rem;position:relative}ul.tabbar li.active{background:#fff}ul.tabbar li:after{background:#ccc;bottom:0;content:"";height:.1rem;left:0;position:absolute;width:100%}ul.tabbar li.active:after{animation:tabbar-border-expand .2s cubic-bezier(.4,0,.4,1) 0s alternate forwards;background:#2196f3;bottom:0;content:"";height:.15rem;left:0;position:absolute}@keyframes tabbar-border-expand{0%{opacity:0;width:0}to{opacity:1;width:100%}}ul.tabbar>li>a{color:#2196f399;font-size:1.3rem;font-variant:small-caps;font-weight:400;line-height:2.4rem;overflow:hidden;padding-left:1rem;padding-right:1rem;position:relative;text-align:center;text-decoration:none}ul.tabbar li.active>a{color:#2196f3}.unread{background-color:#0097a7;border-radius:50%;color:#fff;display:inline-block;font-size:.75rem;font-weight:bolder;height:1.35rem;line-height:1.45rem;margin-left:.5rem;text-align:center;vertical-align:middle;width:1.35rem}.material-icons.as-badge{color:#aaa;font-size:1.15rem;padding-left:.2rem}.badge{align-self:flex-start;background-color:#e8e8e8;border:1px solid silver;border-radius:.2rem;color:#666;display:inline-block;font-family:Roboto Mono,Courier,monospace,sans-serif;font-size:.8rem;margin:.05rem .1rem;padding:.05rem .25rem}.badge.green{background-color:#efe;border-color:#aca;color:#383}.badge.yellow{background-color:#ffe;border-color:#cc9;color:#660}.badge.blue{background-color:#eef;border-color:#aad;color:#339}.badge.red{background-color:#fee;border-color:#c99;color:#933}.badge.magenta{background-color:#fef;border-color:#c9c;color:#939}.lettertile{border-radius:50%;padding-bottom:100%;user-select:none;width:100%}.lettertile>div{align-items:center;border-radius:50%;bottom:0;color:#fafafacc;display:flex;flex-grow:0;flex-shrink:0;justify-content:center;left:0;line-height:1;padding-top:.1em;position:absolute;right:0;text-align:center;text-transform:uppercase;top:0}.lettertile:hover{color:#fff}.lettertile.disabled{opacity:.5}.lt-bg-0{background-color:#ef9a9a}.lt-bg-1{background-color:#90caf9}.lt-bg-2{background-color:#b0bec5}.lt-bg-3{background-color:#b39ddb}.lt-bg-4{background-color:#ffab91}.lt-bg-5{background-color:#a5d6a7}.lt-bg-6{background-color:#eee}.lt-bg-7{background-color:#e6ee9c}.lt-bg-8{background-color:#c5e1a5}.lt-bg-9{background-color:#f0e57d}.lt-bg-10{background-color:#f48fb1}.lt-bg-11{background-color:#9fa8da}.lt-bg-12{background-color:#ffe082}.lt-bg-13{background-color:#bcaaa4}.lt-bg-14{background-color:#80deea}.lt-bg-15{background-color:#ce93d8}.dk-bg-0{background-color:#c62828}.dk-bg-1{background-color:#ad1457}.dk-bg-2{background-color:#6a1b9a}.dk-bg-3{background-color:#4527a0}.dk-bg-4{background-color:#283593}.dk-bg-5{background-color:#1565c0}.dk-bg-6{background-color:#0277bd}.dk-bg-7{background-color:#00838f}.dk-bg-8{background-color:#00695c}.dk-bg-9{background-color:#2e7d32}.dk-bg-10{background-color:#558b2f}.dk-bg-11{background-color:#9e9d24}.dk-bg-12{background-color:#f9a825}.dk-bg-13{background-color:#ff8f00}.dk-bg-14{background-color:#ef6c00}.dk-bg-15{background-color:#d84315}.lt-fg-0{color:#ef9a9a!important}.lt-fg-1{color:#90caf9!important}.lt-fg-2{color:#b0bec5!important}.lt-fg-3{color:#b39ddb!important}.lt-fg-4{color:#ffab91!important}.lt-fg-5{color:#a5d6a7!important}.lt-fg-6{color:#eee!important}.lt-fg-7{color:#e6ee9c!important}.lt-fg-8{color:#c5e1a5!important}.lt-fg-9{color:#f0e57d!important}.lt-fg-10{color:#f48fb1!important}.lt-fg-11{color:#9fa8da!important}.lt-fg-12{color:#ffe082!important}.lt-fg-13{color:#bcaaa4!important}.lt-fg-14{color:#80deea!important}.lt-fg-15{color:#ce93d8!important}.dk-fg-0{color:#c62828!important}.dk-fg-1{color:#ad1457!important}.dk-fg-2{color:#6a1b9a!important}.dk-fg-3{color:#4527a0!important}.dk-fg-4{color:#283593!important}.dk-fg-5{color:#1565c0!important}.dk-fg-6{color:#0277bd!important}.dk-fg-7{color:#00838f!important}.dk-fg-8{color:#00695c!important}.dk-fg-9{color:#2e7d32!important}.dk-fg-10{color:#558b2f!important}.dk-fg-11{color:#9e9d24!important}.dk-fg-12{color:#f9a825!important}.dk-fg-13{color:#ff8f00!important}.dk-fg-14{color:#ef6c00!important}.dk-fg-15{color:#d84315!important}.material-icons{font-size:1.4rem;line-height:1;text-align:center;vertical-align:middle}.material-icons.small{font-size:1rem}.material-icons.medium{font-size:1.2rem}.material-icons.big{font-size:2.2rem}.material-icons.bigger{font-size:3rem}.material-icons.huge{font-size:4rem}.composed-material{display:inline-block;position:relative}.composed-material i:nth-child(2){font-size:85%;font-weight:700;left:39%;position:absolute;top:7%}#self-avatar .material-icons{font-size:2.4rem;line-height:3rem}.avatar-box .material-icons{border-radius:50%;color:#fafafacc;height:inherit;width:inherit}.chip-input{align-items:center;background:#0000;border-bottom:1px solid #ccc;box-shadow:0 1px 0 #0000001a;color:#666;cursor:text;display:flex;flex-grow:1;flex-wrap:wrap;font-size:1.1rem;font-weight:400;justify-content:flex-start;margin:.25rem 0;max-height:10rem;min-height:4rem;outline:none;overflow-y:scroll;text-align:center;transition:all .1s ease-in-out}.chip-input.focused{border-bottom:1px solid #2196f3;box-shadow:0 1px 0 #2196f340}.chip-input>input[type=text]{border:none;box-shadow:none;display:inline-block;flex:1 0 auto;min-width:4rem;width:auto}.chip,.chip-input>input[type=text]{height:1.8rem;line-height:1.8;margin:.125rem}.chip{align-items:center;background-color:#eee;border-radius:.9rem;display:flex;flex:0 0 auto;font-size:90%;max-width:12rem;overflow:hidden}.chip,.chip>span{text-overflow:ellipsis;white-space:nowrap}.chip>span{overflow-x:hidden}.chip.invalid{background-color:#fee;color:#c66}.chip>a{background-color:#aaa;border-radius:50%;color:#eee;display:inline-block;height:1.175rem;line-height:1.15;margin:.3rem;min-width:1.175rem;text-decoration:none;width:1.175rem}.chip>a:focus,.chip>a:hover{background-color:#bbb;color:#fff;text-decoration:none}.chip .avatar-box{font-size:1rem;height:1.8rem;margin-right:.2rem;min-height:1.8rem;min-width:1.8rem;position:relative;width:1.8rem}.chip .avatar-box .material-icons{font-size:1.4rem;line-height:1.8rem}.chip .spacer{display:inline-block;height:1.175rem;margin:.3rem;width:.25rem}.load-spinner-box{--size-small:2.5rem;--size-large:4rem;background-color:#fff;border-radius:50%;box-shadow:.1rem .1rem .15rem 1px #00000040;height:var(--size-small);left:0;margin-left:auto;margin-right:auto;padding:.25rem;position:absolute;right:0;top:5rem;width:var(--size-small);z-index:2}.load-spinner-box.large{height:var(--size-large);width:var(--size-large)}.load-spinner-box.clear{background-color:#fff8;-x-box-shadow:none;box-shadow:.1rem .1rem .15rem 1px #0000001f}.load-spinner-box.centered{top:calc(var(--size-small)/2 - .25rem)}.load-spinner-box.large.centered{top:calc(var(--size-large)/2 - .25rem)}.loader-spinner{animation:spin 1.5s linear infinite;border:.35rem solid #f3f3f3;border-radius:50%;border-top-color:#1e88e5;height:2rem;width:2rem}.load-spinner-box.large .loader-spinner{height:3.5rem;width:3.5rem}@keyframes spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.uploader{display:flex}.uploader>div{background-color:#cfd8dc;border-radius:.1rem;height:.6rem;line-height:0;margin:.35rem;padding:.15rem;position:relative;width:6rem}.uploader>div>span{background-color:#1e88e5;border-radius:.08rem;display:inline-block;height:.3rem}.highlight{color:teal;font-weight:bolder}.highlight .preview{color:#5f9ea0;font-weight:inherit}.cropper{align-self:center;height:21rem;margin:1rem auto auto;transform:translateZ(0)}.cropper,.cropper .bounding-box{border-radius:.25rem;position:relative;width:18rem}.cropper .bounding-box{background-color:#999;border:2px solid #1e88e5;box-shadow:1px 1px 3px grey;height:18rem;overflow:hidden;z-index:1}.cropper .preview{max-height:none;max-width:none;position:absolute;z-index:-1}.cropper .cutout{border:1px dashed #999;bottom:0;box-shadow:0 0 150rem 150rem #e6f6ffa8;height:17rem;left:0;margin:auto;position:absolute;right:0;top:0;width:17rem;z-index:0}.cropper .cutout.circle{border-radius:50%}.cropper .overlay{cursor:move;position:absolute;touch-action:none;z-index:1}.cropper .zoom-wrapper{height:2rem;margin:1rem auto;text-align:center;width:80%}.cropper .zoom{box-shadow:none;pointer-events:none;z-index:2}.cropper .zoom:focus{outline:none}.reply-quote{border-left:.25rem solid #039be5;border-radius:.25rem;color:#666;cursor:pointer;font-weight:lighter;line-height:1.5em;padding:.15rem .5rem .25rem;position:relative}.chat-box .bubble .reply-quote{margin:.15rem -.75rem .3rem}.chat-box .bubble .reply-quote:first-child{margin-top:-.25rem}.chat-box .left .reply-quote{background-color:#fff6}.chat-box .right .reply-quote{background-color:#8080801f}.reply-quote .inline-image{margin-bottom:.1rem;vertical-align:middle}.reply-quote img.inline-image:before{content:""}#reply-quote-preview{align-items:center;display:flex}#reply-quote-preview .reply-quote{background-color:#fafafa;cursor:auto;margin:.35rem .5rem 0 0;width:100%}#reply-quote-preview .cancel{min-width:2.4rem;text-align:center}#reply-quote-preview .inline-image{background-color:#ccc}#reply-quote-preview img.inline-image:before{content:""}#send-message-panel #reply-quote-preview{width:100%}#send-message-panel #reply-quote-preview .reply-quote{margin-bottom:.35rem}.forwarding-quote{font-size:200%;line-height:200%}.mention{font-weight:500}.forward-dialog{background-color:#fff;border-radius:.3rem;box-shadow:.15rem .15rem 1.5rem #00000073;height:80%;margin:auto 1rem;overflow:hidden;padding:.5rem;position:relative;width:24rem}.forward-dialog .scrollable-panel{height:80%}.audio{align-items:center;background-color:#eee;border-radius:1.5rem;display:flex;flex:none;height:3rem;margin-left:auto}.audio canvas{height:2.6rem;margin-right:2rem;width:14rem}.audio canvas.playback{margin-right:0}.audio .duration{font-size:large}.audio-player{align-items:center;display:flex}.audio-player .material-icons.large{color:#667575cc;font-size:2.4rem}.audio-player .material-icons.disabled{color:#999c;cursor:default}.audio-player .playback{height:2.6rem;width:14rem}.audio-player canvas.playback{display:block}.audio-player div.playback{align-items:center;color:#757575cc;display:flex;font-size:small;justify-content:center}.audio-player .timer{color:#666c;font-size:smaller}#pinned-wrapper{margin-right:1rem}#pinned-wrapper,.pinned{align-items:center;display:flex;height:100%;position:relative}.pinned{background-color:#fafafa;background-position:50%;border-radius:0 .25rem .25rem 0;color:#666;cursor:pointer;font-weight:lighter;line-height:1.5em;min-width:24rem;overflow-x:hidden;padding:.15rem .5rem .25rem;text-overflow:ellipsis;transition:background .4s;width:100%}.pinned:hover{background-color:#fafdff}.pinned:active{background-color:#d8e8ff;transition:background 0s}.pinned-scroll{align-items:center;background-color:#eeee;border-radius:.25rem 0 0 .25rem;display:flex;flex-direction:column;height:100%;justify-content:space-evenly;margin-left:.35rem;padding:.1rem;position:relative}.pinned-scroll .dot{background-color:#999;border-radius:50%;height:.3rem;width:.3rem}.pinned-scroll .adot{background-color:#039be5;border-radius:50%;height:.45rem;width:.45rem}#pinned-wrapper .menuTrigger.upper{top:.25rem}#pinned-wrapper .menuTrigger.lower{bottom:.25rem}#pinned-wrapper:hover .menuTrigger{opacity:.9}#pinned-wrapper:hover .menuTrigger a{color:#757575}.drag-n-drop{align-items:center;background-color:#fffffff2;border:.15rem dashed grey;border-radius:1rem;bottom:1.5rem;color:grey;display:flex;font-size:2rem;justify-content:center;left:1.5rem;outline:.5rem solid #fffffff2;position:absolute;right:1.5rem;top:1.5rem;z-index:3}.country-flag{display:inline-block;font-size:larger}.dial-code{cursor:pointer;display:inline-block;margin-bottom:.15rem;vertical-align:middle;white-space:nowrap}ul.phone-country-selector{list-style:none;overflow-x:hidden}ul.phone-country-selector>li{cursor:pointer;font-weight:lighter;padding:.25rem .5rem .15rem;position:relative;width:100%}ul.phone-country-selector>li:hover{background-color:#eceff1}ul.phone-country-selector>li.selected{background-color:#cfd8dc}ul.phone-country-selector .dial-code{color:#1e88e5;font-weight:400;position:absolute;right:.5rem}ul.phone-country-selector span{display:inline-block}ul.phone-country-selector span.country{overflow-x:hidden;text-overflow:ellipsis}@media (min-width:1440px){#app-container{max-width:114rem}}@media (max-width:960px){#mountPoint{padding:0}.pinned{min-width:12rem}}@media (max-width:640px){#app-container{border-radius:0;box-shadow:none;width:100%}#info-view,#sidepanel{width:100%}.forward-dialog{border-radius:.3rem .3rem 0 0;margin:auto 0 0;width:100%}.menuTrigger{opacity:.3}#send-message-input{transition-property:-tinode-mobile}#pinned-wrapper{height:3.5rem;margin:.25rem}.pinned{min-width:unset}} \ No newline at end of file diff --git a/src/views/messages-view.jsx b/src/views/messages-view.jsx index 712815c7..b7239927 100644 --- a/src/views/messages-view.jsx +++ b/src/views/messages-view.jsx @@ -1633,6 +1633,7 @@ class MessagesView extends React.Component { }
{lastSeen}
+
{!this.props.displayMobile ? > 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if ((c & 0xfc00) === 0xd800 &&\r\n i + 1 < str.length &&\r\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\r\n // Surrogate Pair\r\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Turns an array of numbers into the string given by the concatenation of the\r\n * characters to which the numbers correspond.\r\n * @param bytes Array of numbers representing characters.\r\n * @return Stringification of the array.\r\n */\r\nconst byteArrayToString = function (bytes) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let pos = 0, c = 0;\r\n while (pos < bytes.length) {\r\n const c1 = bytes[pos++];\r\n if (c1 < 128) {\r\n out[c++] = String.fromCharCode(c1);\r\n }\r\n else if (c1 > 191 && c1 < 224) {\r\n const c2 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\r\n }\r\n else if (c1 > 239 && c1 < 365) {\r\n // Surrogate Pair\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n const c4 = bytes[pos++];\r\n const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\r\n 0x10000;\r\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\r\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\r\n }\r\n else {\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\r\n }\r\n }\r\n return out.join('');\r\n};\r\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\r\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\r\n// Static lookup maps, lazily populated by init_()\r\nconst base64 = {\r\n /**\r\n * Maps bytes to characters.\r\n */\r\n byteToCharMap_: null,\r\n /**\r\n * Maps characters to bytes.\r\n */\r\n charToByteMap_: null,\r\n /**\r\n * Maps bytes to websafe characters.\r\n * @private\r\n */\r\n byteToCharMapWebSafe_: null,\r\n /**\r\n * Maps websafe characters to bytes.\r\n * @private\r\n */\r\n charToByteMapWebSafe_: null,\r\n /**\r\n * Our default alphabet, shared between\r\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\r\n */\r\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\r\n /**\r\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\r\n */\r\n get ENCODED_VALS() {\r\n return this.ENCODED_VALS_BASE + '+/=';\r\n },\r\n /**\r\n * Our websafe alphabet.\r\n */\r\n get ENCODED_VALS_WEBSAFE() {\r\n return this.ENCODED_VALS_BASE + '-_.';\r\n },\r\n /**\r\n * Whether this browser supports the atob and btoa functions. This extension\r\n * started at Mozilla but is now implemented by many browsers. We use the\r\n * ASSUME_* variables to avoid pulling in the full useragent detection library\r\n * but still allowing the standard per-browser compilations.\r\n *\r\n */\r\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\r\n /**\r\n * Base64-encode an array of bytes.\r\n *\r\n * @param input An array of bytes (numbers with\r\n * value in [0, 255]) to encode.\r\n * @param webSafe Boolean indicating we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeByteArray(input, webSafe) {\r\n if (!Array.isArray(input)) {\r\n throw Error('encodeByteArray takes an array as a parameter');\r\n }\r\n this.init_();\r\n const byteToCharMap = webSafe\r\n ? this.byteToCharMapWebSafe_\r\n : this.byteToCharMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length; i += 3) {\r\n const byte1 = input[i];\r\n const haveByte2 = i + 1 < input.length;\r\n const byte2 = haveByte2 ? input[i + 1] : 0;\r\n const haveByte3 = i + 2 < input.length;\r\n const byte3 = haveByte3 ? input[i + 2] : 0;\r\n const outByte1 = byte1 >> 2;\r\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\r\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\r\n let outByte4 = byte3 & 0x3f;\r\n if (!haveByte3) {\r\n outByte4 = 64;\r\n if (!haveByte2) {\r\n outByte3 = 64;\r\n }\r\n }\r\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\r\n }\r\n return output.join('');\r\n },\r\n /**\r\n * Base64-encode a string.\r\n *\r\n * @param input A string to encode.\r\n * @param webSafe If true, we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return btoa(input);\r\n }\r\n return this.encodeByteArray(stringToByteArray$1(input), webSafe);\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * @param input to decode.\r\n * @param webSafe True if we should use the\r\n * alternative alphabet.\r\n * @return string representing the decoded value.\r\n */\r\n decodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return atob(input);\r\n }\r\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * In base-64 decoding, groups of four characters are converted into three\r\n * bytes. If the encoder did not apply padding, the input length may not\r\n * be a multiple of 4.\r\n *\r\n * In this case, the last group will have fewer than 4 characters, and\r\n * padding will be inferred. If the group has one or two characters, it decodes\r\n * to one byte. If the group has three characters, it decodes to two bytes.\r\n *\r\n * @param input Input to decode.\r\n * @param webSafe True if we should use the web-safe alphabet.\r\n * @return bytes representing the decoded value.\r\n */\r\n decodeStringToByteArray(input, webSafe) {\r\n this.init_();\r\n const charToByteMap = webSafe\r\n ? this.charToByteMapWebSafe_\r\n : this.charToByteMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length;) {\r\n const byte1 = charToByteMap[input.charAt(i++)];\r\n const haveByte2 = i < input.length;\r\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\r\n ++i;\r\n const haveByte3 = i < input.length;\r\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n const haveByte4 = i < input.length;\r\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\r\n throw new DecodeBase64StringError();\r\n }\r\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\r\n output.push(outByte1);\r\n if (byte3 !== 64) {\r\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\r\n output.push(outByte2);\r\n if (byte4 !== 64) {\r\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\r\n output.push(outByte3);\r\n }\r\n }\r\n }\r\n return output;\r\n },\r\n /**\r\n * Lazy static initialization function. Called before\r\n * accessing any of the static map variables.\r\n * @private\r\n */\r\n init_() {\r\n if (!this.byteToCharMap_) {\r\n this.byteToCharMap_ = {};\r\n this.charToByteMap_ = {};\r\n this.byteToCharMapWebSafe_ = {};\r\n this.charToByteMapWebSafe_ = {};\r\n // We want quick mappings back and forth, so we precompute two maps.\r\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\r\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\r\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\r\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\r\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\r\n // Be forgiving when decoding and correctly decode both encodings.\r\n if (i >= this.ENCODED_VALS_BASE.length) {\r\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\r\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\r\n }\r\n }\r\n }\r\n }\r\n};\r\n/**\r\n * An error encountered while decoding base64 string.\r\n */\r\nclass DecodeBase64StringError extends Error {\r\n constructor() {\r\n super(...arguments);\r\n this.name = 'DecodeBase64StringError';\r\n }\r\n}\r\n/**\r\n * URL-safe base64 encoding\r\n */\r\nconst base64Encode = function (str) {\r\n const utf8Bytes = stringToByteArray$1(str);\r\n return base64.encodeByteArray(utf8Bytes, true);\r\n};\r\n/**\r\n * URL-safe base64 encoding (without \".\" padding in the end).\r\n * e.g. Used in JSON Web Token (JWT) parts.\r\n */\r\nconst base64urlEncodeWithoutPadding = function (str) {\r\n // Use base64url encoding and remove padding in the end (dot characters).\r\n return base64Encode(str).replace(/\\./g, '');\r\n};\r\n/**\r\n * URL-safe base64 decoding\r\n *\r\n * NOTE: DO NOT use the global atob() function - it does NOT support the\r\n * base64Url variant encoding.\r\n *\r\n * @param str To be decoded\r\n * @return Decoded result, if possible\r\n */\r\nconst base64Decode = function (str) {\r\n try {\r\n return base64.decodeString(str, true);\r\n }\r\n catch (e) {\r\n console.error('base64Decode failed: ', e);\r\n }\r\n return null;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Do a deep-copy of basic JavaScript Objects or Arrays.\r\n */\r\nfunction deepCopy(value) {\r\n return deepExtend(undefined, value);\r\n}\r\n/**\r\n * Copy properties from source to target (recursively allows extension\r\n * of Objects and Arrays). Scalar values in the target are over-written.\r\n * If target is undefined, an object of the appropriate type will be created\r\n * (and returned).\r\n *\r\n * We recursively copy all child properties of plain Objects in the source- so\r\n * that namespace- like dictionaries are merged.\r\n *\r\n * Note that the target can be a function, in which case the properties in\r\n * the source Object are copied onto it as static properties of the Function.\r\n *\r\n * Note: we don't merge __proto__ to prevent prototype pollution\r\n */\r\nfunction deepExtend(target, source) {\r\n if (!(source instanceof Object)) {\r\n return source;\r\n }\r\n switch (source.constructor) {\r\n case Date:\r\n // Treat Dates like scalars; if the target date object had any child\r\n // properties - they will be lost!\r\n const dateValue = source;\r\n return new Date(dateValue.getTime());\r\n case Object:\r\n if (target === undefined) {\r\n target = {};\r\n }\r\n break;\r\n case Array:\r\n // Always copy the array source and overwrite the target.\r\n target = [];\r\n break;\r\n default:\r\n // Not a plain Object - treat it as a scalar.\r\n return source;\r\n }\r\n for (const prop in source) {\r\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\r\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\r\n continue;\r\n }\r\n target[prop] = deepExtend(target[prop], source[prop]);\r\n }\r\n return target;\r\n}\r\nfunction isValidKey(key) {\r\n return key !== '__proto__';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Polyfill for `globalThis` object.\r\n * @returns the `globalThis` object for the given environment.\r\n * @public\r\n */\r\nfunction getGlobal() {\r\n if (typeof self !== 'undefined') {\r\n return self;\r\n }\r\n if (typeof window !== 'undefined') {\r\n return window;\r\n }\r\n if (typeof global !== 'undefined') {\r\n return global;\r\n }\r\n throw new Error('Unable to locate global object.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;\r\n/**\r\n * Attempt to read defaults from a JSON string provided to\r\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\r\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\r\n * The dots are in parens because certain compilers (Vite?) cannot\r\n * handle seeing that variable in comments.\r\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\r\n */\r\nconst getDefaultsFromEnvVariable = () => {\r\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\r\n return;\r\n }\r\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\r\n if (defaultsJsonString) {\r\n return JSON.parse(defaultsJsonString);\r\n }\r\n};\r\nconst getDefaultsFromCookie = () => {\r\n if (typeof document === 'undefined') {\r\n return;\r\n }\r\n let match;\r\n try {\r\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\r\n }\r\n catch (e) {\r\n // Some environments such as Angular Universal SSR have a\r\n // `document` object but error on accessing `document.cookie`.\r\n return;\r\n }\r\n const decoded = match && base64Decode(match[1]);\r\n return decoded && JSON.parse(decoded);\r\n};\r\n/**\r\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\r\n * (1) if such an object exists as a property of `globalThis`\r\n * (2) if such an object was provided on a shell environment variable\r\n * (3) if such an object exists in a cookie\r\n * @public\r\n */\r\nconst getDefaults = () => {\r\n try {\r\n return (getDefaultsFromGlobal() ||\r\n getDefaultsFromEnvVariable() ||\r\n getDefaultsFromCookie());\r\n }\r\n catch (e) {\r\n /**\r\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\r\n * to any environment case we have not accounted for. Log to\r\n * info instead of swallowing so we can find these unknown cases\r\n * and add paths for them if needed.\r\n */\r\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\r\n return;\r\n }\r\n};\r\n/**\r\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHost = (productName) => { var _a, _b; return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; };\r\n/**\r\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHostnameAndPort = (productName) => {\r\n const host = getDefaultEmulatorHost(productName);\r\n if (!host) {\r\n return undefined;\r\n }\r\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\r\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\r\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\r\n }\r\n // eslint-disable-next-line no-restricted-globals\r\n const port = parseInt(host.substring(separatorIndex + 1), 10);\r\n if (host[0] === '[') {\r\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\r\n return [host.substring(1, separatorIndex - 1), port];\r\n }\r\n else {\r\n return [host.substring(0, separatorIndex), port];\r\n }\r\n};\r\n/**\r\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\r\n * @public\r\n */\r\nconst getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };\r\n/**\r\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\r\n * prefixed by \"_\")\r\n * @public\r\n */\r\nconst getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Deferred {\r\n constructor() {\r\n this.reject = () => { };\r\n this.resolve = () => { };\r\n this.promise = new Promise((resolve, reject) => {\r\n this.resolve = resolve;\r\n this.reject = reject;\r\n });\r\n }\r\n /**\r\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\r\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\r\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\r\n */\r\n wrapCallback(callback) {\r\n return (error, value) => {\r\n if (error) {\r\n this.reject(error);\r\n }\r\n else {\r\n this.resolve(value);\r\n }\r\n if (typeof callback === 'function') {\r\n // Attaching noop handler just in case developer wasn't expecting\r\n // promises\r\n this.promise.catch(() => { });\r\n // Some of our callbacks don't expect a value and our own tests\r\n // assert that the parameter length is 1\r\n if (callback.length === 1) {\r\n callback(error);\r\n }\r\n else {\r\n callback(error, value);\r\n }\r\n }\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createMockUserToken(token, projectId) {\r\n if (token.uid) {\r\n throw new Error('The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.');\r\n }\r\n // Unsecured JWTs use \"none\" as the algorithm.\r\n const header = {\r\n alg: 'none',\r\n type: 'JWT'\r\n };\r\n const project = projectId || 'demo-project';\r\n const iat = token.iat || 0;\r\n const sub = token.sub || token.user_id;\r\n if (!sub) {\r\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\r\n }\r\n const payload = Object.assign({ \r\n // Set all required fields to decent defaults\r\n iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {\r\n sign_in_provider: 'custom',\r\n identities: {}\r\n } }, token);\r\n // Unsecured JWTs use the empty string as a signature.\r\n const signature = '';\r\n return [\r\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\r\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\r\n signature\r\n ].join('.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns navigator.userAgent string or '' if it's not defined.\r\n * @return user agent string\r\n */\r\nfunction getUA() {\r\n if (typeof navigator !== 'undefined' &&\r\n typeof navigator['userAgent'] === 'string') {\r\n return navigator['userAgent'];\r\n }\r\n else {\r\n return '';\r\n }\r\n}\r\n/**\r\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\r\n *\r\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\r\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\r\n * wait for a callback.\r\n */\r\nfunction isMobileCordova() {\r\n return (typeof window !== 'undefined' &&\r\n // @ts-ignore Setting up an broadly applicable index signature for Window\r\n // just to deal with this case would probably be a bad idea.\r\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\r\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\r\n}\r\n/**\r\n * Detect Node.js.\r\n *\r\n * @return true if Node.js environment is detected or specified.\r\n */\r\n// Node detection logic from: https://github.com/iliakan/detect-node/\r\nfunction isNode() {\r\n var _a;\r\n const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment;\r\n if (forceEnvironment === 'node') {\r\n return true;\r\n }\r\n else if (forceEnvironment === 'browser') {\r\n return false;\r\n }\r\n try {\r\n return (Object.prototype.toString.call(global.process) === '[object process]');\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Detect Browser Environment\r\n */\r\nfunction isBrowser() {\r\n return typeof self === 'object' && self.self === self;\r\n}\r\nfunction isBrowserExtension() {\r\n const runtime = typeof chrome === 'object'\r\n ? chrome.runtime\r\n : typeof browser === 'object'\r\n ? browser.runtime\r\n : undefined;\r\n return typeof runtime === 'object' && runtime.id !== undefined;\r\n}\r\n/**\r\n * Detect React Native.\r\n *\r\n * @return true if ReactNative environment is detected.\r\n */\r\nfunction isReactNative() {\r\n return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\r\n}\r\n/** Detects Electron apps. */\r\nfunction isElectron() {\r\n return getUA().indexOf('Electron/') >= 0;\r\n}\r\n/** Detects Internet Explorer. */\r\nfunction isIE() {\r\n const ua = getUA();\r\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\r\n}\r\n/** Detects Universal Windows Platform apps. */\r\nfunction isUWP() {\r\n return getUA().indexOf('MSAppHost/') >= 0;\r\n}\r\n/**\r\n * Detect whether the current SDK build is the Node version.\r\n *\r\n * @return true if it's the Node SDK build.\r\n */\r\nfunction isNodeSdk() {\r\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\r\n}\r\n/** Returns true if we are running in Safari. */\r\nfunction isSafari() {\r\n return (!isNode() &&\r\n navigator.userAgent.includes('Safari') &&\r\n !navigator.userAgent.includes('Chrome'));\r\n}\r\n/**\r\n * This method checks if indexedDB is supported by current browser/service worker context\r\n * @return true if indexedDB is supported by current browser/service worker context\r\n */\r\nfunction isIndexedDBAvailable() {\r\n try {\r\n return typeof indexedDB === 'object';\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\r\n * if errors occur during the database open operation.\r\n *\r\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\r\n * private browsing)\r\n */\r\nfunction validateIndexedDBOpenable() {\r\n return new Promise((resolve, reject) => {\r\n try {\r\n let preExist = true;\r\n const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';\r\n const request = self.indexedDB.open(DB_CHECK_NAME);\r\n request.onsuccess = () => {\r\n request.result.close();\r\n // delete database only when it doesn't pre-exist\r\n if (!preExist) {\r\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\r\n }\r\n resolve(true);\r\n };\r\n request.onupgradeneeded = () => {\r\n preExist = false;\r\n };\r\n request.onerror = () => {\r\n var _a;\r\n reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');\r\n };\r\n }\r\n catch (error) {\r\n reject(error);\r\n }\r\n });\r\n}\r\n/**\r\n *\r\n * This method checks whether cookie is enabled within current browser\r\n * @return true if cookie is enabled within current browser\r\n */\r\nfunction areCookiesEnabled() {\r\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\r\n return false;\r\n }\r\n return true;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Standardized Firebase Error.\r\n *\r\n * Usage:\r\n *\r\n * // Typescript string literals for type-safe codes\r\n * type Err =\r\n * 'unknown' |\r\n * 'object-not-found'\r\n * ;\r\n *\r\n * // Closure enum for type-safe error codes\r\n * // at-enum {string}\r\n * var Err = {\r\n * UNKNOWN: 'unknown',\r\n * OBJECT_NOT_FOUND: 'object-not-found',\r\n * }\r\n *\r\n * let errors: Map = {\r\n * 'generic-error': \"Unknown error\",\r\n * 'file-not-found': \"Could not find file: {$file}\",\r\n * };\r\n *\r\n * // Type-safe function - must pass a valid error code as param.\r\n * let error = new ErrorFactory('service', 'Service', errors);\r\n *\r\n * ...\r\n * throw error.create(Err.GENERIC);\r\n * ...\r\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\r\n * ...\r\n * // Service: Could not file file: foo.txt (service/file-not-found).\r\n *\r\n * catch (e) {\r\n * assert(e.message === \"Could not find file: foo.txt.\");\r\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\r\n * console.log(\"Could not read file: \" + e['file']);\r\n * }\r\n * }\r\n */\r\nconst ERROR_NAME = 'FirebaseError';\r\n// Based on code from:\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\r\nclass FirebaseError extends Error {\r\n constructor(\r\n /** The error code for this error. */\r\n code, message, \r\n /** Custom data for this error. */\r\n customData) {\r\n super(message);\r\n this.code = code;\r\n this.customData = customData;\r\n /** The custom name for all FirebaseErrors. */\r\n this.name = ERROR_NAME;\r\n // Fix For ES5\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, FirebaseError.prototype);\r\n // Maintains proper stack trace for where our error was thrown.\r\n // Only available on V8.\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\r\n }\r\n }\r\n}\r\nclass ErrorFactory {\r\n constructor(service, serviceName, errors) {\r\n this.service = service;\r\n this.serviceName = serviceName;\r\n this.errors = errors;\r\n }\r\n create(code, ...data) {\r\n const customData = data[0] || {};\r\n const fullCode = `${this.service}/${code}`;\r\n const template = this.errors[code];\r\n const message = template ? replaceTemplate(template, customData) : 'Error';\r\n // Service Name: Error message (service/code).\r\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\r\n const error = new FirebaseError(fullCode, fullMessage, customData);\r\n return error;\r\n }\r\n}\r\nfunction replaceTemplate(template, data) {\r\n return template.replace(PATTERN, (_, key) => {\r\n const value = data[key];\r\n return value != null ? String(value) : `<${key}?>`;\r\n });\r\n}\r\nconst PATTERN = /\\{\\$([^}]+)}/g;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Evaluates a JSON string into a javascript object.\r\n *\r\n * @param {string} str A string containing JSON.\r\n * @return {*} The javascript object representing the specified JSON.\r\n */\r\nfunction jsonEval(str) {\r\n return JSON.parse(str);\r\n}\r\n/**\r\n * Returns JSON representing a javascript object.\r\n * @param {*} data Javascript object to be stringified.\r\n * @return {string} The JSON contents of the object.\r\n */\r\nfunction stringify(data) {\r\n return JSON.stringify(data);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Decodes a Firebase auth. token into constituent parts.\r\n *\r\n * Notes:\r\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst decode = function (token) {\r\n let header = {}, claims = {}, data = {}, signature = '';\r\n try {\r\n const parts = token.split('.');\r\n header = jsonEval(base64Decode(parts[0]) || '');\r\n claims = jsonEval(base64Decode(parts[1]) || '');\r\n signature = parts[2];\r\n data = claims['d'] || {};\r\n delete claims['d'];\r\n }\r\n catch (e) { }\r\n return {\r\n header,\r\n claims,\r\n data,\r\n signature\r\n };\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\r\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidTimestamp = function (token) {\r\n const claims = decode(token).claims;\r\n const now = Math.floor(new Date().getTime() / 1000);\r\n let validSince = 0, validUntil = 0;\r\n if (typeof claims === 'object') {\r\n if (claims.hasOwnProperty('nbf')) {\r\n validSince = claims['nbf'];\r\n }\r\n else if (claims.hasOwnProperty('iat')) {\r\n validSince = claims['iat'];\r\n }\r\n if (claims.hasOwnProperty('exp')) {\r\n validUntil = claims['exp'];\r\n }\r\n else {\r\n // token will expire after 24h by default\r\n validUntil = validSince + 86400;\r\n }\r\n }\r\n return (!!now &&\r\n !!validSince &&\r\n !!validUntil &&\r\n now >= validSince &&\r\n now <= validUntil);\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\r\n *\r\n * Notes:\r\n * - May return null if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst issuedAtTime = function (token) {\r\n const claims = decode(token).claims;\r\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\r\n return claims['iat'];\r\n }\r\n return null;\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidFormat = function (token) {\r\n const decoded = decode(token), claims = decoded.claims;\r\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\r\n};\r\n/**\r\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isAdmin = function (token) {\r\n const claims = decode(token).claims;\r\n return typeof claims === 'object' && claims['admin'] === true;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction contains(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\nfunction safeGet(obj, key) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return obj[key];\r\n }\r\n else {\r\n return undefined;\r\n }\r\n}\r\nfunction isEmpty(obj) {\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction map(obj, fn, contextObj) {\r\n const res = {};\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n res[key] = fn.call(contextObj, obj[key], key, obj);\r\n }\r\n }\r\n return res;\r\n}\r\n/**\r\n * Deep equal two objects. Support Arrays and Objects.\r\n */\r\nfunction deepEqual(a, b) {\r\n if (a === b) {\r\n return true;\r\n }\r\n const aKeys = Object.keys(a);\r\n const bKeys = Object.keys(b);\r\n for (const k of aKeys) {\r\n if (!bKeys.includes(k)) {\r\n return false;\r\n }\r\n const aProp = a[k];\r\n const bProp = b[k];\r\n if (isObject(aProp) && isObject(bProp)) {\r\n if (!deepEqual(aProp, bProp)) {\r\n return false;\r\n }\r\n }\r\n else if (aProp !== bProp) {\r\n return false;\r\n }\r\n }\r\n for (const k of bKeys) {\r\n if (!aKeys.includes(k)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isObject(thing) {\r\n return thing !== null && typeof thing === 'object';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\r\n * @internal\r\n */\r\nfunction promiseWithTimeout(promise, timeInMS = 2000) {\r\n const deferredPromise = new Deferred();\r\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\r\n promise.then(deferredPromise.resolve, deferredPromise.reject);\r\n return deferredPromise.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\r\n * params object (e.g. {arg: 'val', arg2: 'val2'})\r\n * Note: You must prepend it with ? when adding it to a URL.\r\n */\r\nfunction querystring(querystringParams) {\r\n const params = [];\r\n for (const [key, value] of Object.entries(querystringParams)) {\r\n if (Array.isArray(value)) {\r\n value.forEach(arrayVal => {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\r\n });\r\n }\r\n else {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\r\n }\r\n }\r\n return params.length ? '&' + params.join('&') : '';\r\n}\r\n/**\r\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\r\n * (e.g. {arg: 'val', arg2: 'val2'})\r\n */\r\nfunction querystringDecode(querystring) {\r\n const obj = {};\r\n const tokens = querystring.replace(/^\\?/, '').split('&');\r\n tokens.forEach(token => {\r\n if (token) {\r\n const [key, value] = token.split('=');\r\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\r\n }\r\n });\r\n return obj;\r\n}\r\n/**\r\n * Extract the query string part of a URL, including the leading question mark (if present).\r\n */\r\nfunction extractQuerystring(url) {\r\n const queryStart = url.indexOf('?');\r\n if (!queryStart) {\r\n return '';\r\n }\r\n const fragmentStart = url.indexOf('#', queryStart);\r\n return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n * var sha1 = new sha1();\r\n * sha1.update(bytes);\r\n * var hash = sha1.digest();\r\n *\r\n * Performance:\r\n * Chrome 23: ~400 Mbit/s\r\n * Firefox 16: ~250 Mbit/s\r\n *\r\n */\r\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\nclass Sha1 {\r\n constructor() {\r\n /**\r\n * Holds the previous values of accumulated variables a-e in the compress_\r\n * function.\r\n * @private\r\n */\r\n this.chain_ = [];\r\n /**\r\n * A buffer holding the partially computed hash result.\r\n * @private\r\n */\r\n this.buf_ = [];\r\n /**\r\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\r\n * as the message schedule in the docs.\r\n * @private\r\n */\r\n this.W_ = [];\r\n /**\r\n * Contains data needed to pad messages less than 64 bytes.\r\n * @private\r\n */\r\n this.pad_ = [];\r\n /**\r\n * @private {number}\r\n */\r\n this.inbuf_ = 0;\r\n /**\r\n * @private {number}\r\n */\r\n this.total_ = 0;\r\n this.blockSize = 512 / 8;\r\n this.pad_[0] = 128;\r\n for (let i = 1; i < this.blockSize; ++i) {\r\n this.pad_[i] = 0;\r\n }\r\n this.reset();\r\n }\r\n reset() {\r\n this.chain_[0] = 0x67452301;\r\n this.chain_[1] = 0xefcdab89;\r\n this.chain_[2] = 0x98badcfe;\r\n this.chain_[3] = 0x10325476;\r\n this.chain_[4] = 0xc3d2e1f0;\r\n this.inbuf_ = 0;\r\n this.total_ = 0;\r\n }\r\n /**\r\n * Internal compress helper function.\r\n * @param buf Block to compress.\r\n * @param offset Offset of the block in the buffer.\r\n * @private\r\n */\r\n compress_(buf, offset) {\r\n if (!offset) {\r\n offset = 0;\r\n }\r\n const W = this.W_;\r\n // get 16 big endian words\r\n if (typeof buf === 'string') {\r\n for (let i = 0; i < 16; i++) {\r\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\r\n // have a bug that turns the post-increment ++ operator into pre-increment\r\n // during JIT compilation. We have code that depends heavily on SHA-1 for\r\n // correctness and which is affected by this bug, so I've removed all uses\r\n // of post-increment ++ in which the result value is used. We can revert\r\n // this change once the Safari bug\r\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\r\n // most clients have been updated.\r\n W[i] =\r\n (buf.charCodeAt(offset) << 24) |\r\n (buf.charCodeAt(offset + 1) << 16) |\r\n (buf.charCodeAt(offset + 2) << 8) |\r\n buf.charCodeAt(offset + 3);\r\n offset += 4;\r\n }\r\n }\r\n else {\r\n for (let i = 0; i < 16; i++) {\r\n W[i] =\r\n (buf[offset] << 24) |\r\n (buf[offset + 1] << 16) |\r\n (buf[offset + 2] << 8) |\r\n buf[offset + 3];\r\n offset += 4;\r\n }\r\n }\r\n // expand to 80 words\r\n for (let i = 16; i < 80; i++) {\r\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\r\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\r\n }\r\n let a = this.chain_[0];\r\n let b = this.chain_[1];\r\n let c = this.chain_[2];\r\n let d = this.chain_[3];\r\n let e = this.chain_[4];\r\n let f, k;\r\n // TODO(user): Try to unroll this loop to speed up the computation.\r\n for (let i = 0; i < 80; i++) {\r\n if (i < 40) {\r\n if (i < 20) {\r\n f = d ^ (b & (c ^ d));\r\n k = 0x5a827999;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0x6ed9eba1;\r\n }\r\n }\r\n else {\r\n if (i < 60) {\r\n f = (b & c) | (d & (b | c));\r\n k = 0x8f1bbcdc;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0xca62c1d6;\r\n }\r\n }\r\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\r\n e = d;\r\n d = c;\r\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\r\n b = a;\r\n a = t;\r\n }\r\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\r\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\r\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\r\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\r\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\r\n }\r\n update(bytes, length) {\r\n // TODO(johnlenz): tighten the function signature and remove this check\r\n if (bytes == null) {\r\n return;\r\n }\r\n if (length === undefined) {\r\n length = bytes.length;\r\n }\r\n const lengthMinusBlock = length - this.blockSize;\r\n let n = 0;\r\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\r\n const buf = this.buf_;\r\n let inbuf = this.inbuf_;\r\n // The outer while loop should execute at most twice.\r\n while (n < length) {\r\n // When we have no data in the block to top up, we can directly process the\r\n // input buffer (assuming it contains sufficient data). This gives ~25%\r\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\r\n // the data is provided in large chunks (or in multiples of 64 bytes).\r\n if (inbuf === 0) {\r\n while (n <= lengthMinusBlock) {\r\n this.compress_(bytes, n);\r\n n += this.blockSize;\r\n }\r\n }\r\n if (typeof bytes === 'string') {\r\n while (n < length) {\r\n buf[inbuf] = bytes.charCodeAt(n);\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n while (n < length) {\r\n buf[inbuf] = bytes[n];\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n this.inbuf_ = inbuf;\r\n this.total_ += length;\r\n }\r\n /** @override */\r\n digest() {\r\n const digest = [];\r\n let totalBits = this.total_ * 8;\r\n // Add pad 0x80 0x00*.\r\n if (this.inbuf_ < 56) {\r\n this.update(this.pad_, 56 - this.inbuf_);\r\n }\r\n else {\r\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\r\n }\r\n // Add # bits.\r\n for (let i = this.blockSize - 1; i >= 56; i--) {\r\n this.buf_[i] = totalBits & 255;\r\n totalBits /= 256; // Don't use bit-shifting here!\r\n }\r\n this.compress_(this.buf_);\r\n let n = 0;\r\n for (let i = 0; i < 5; i++) {\r\n for (let j = 24; j >= 0; j -= 8) {\r\n digest[n] = (this.chain_[i] >> j) & 255;\r\n ++n;\r\n }\r\n }\r\n return digest;\r\n }\r\n}\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\nfunction createSubscribe(executor, onNoObservers) {\r\n const proxy = new ObserverProxy(executor, onNoObservers);\r\n return proxy.subscribe.bind(proxy);\r\n}\r\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\r\nclass ObserverProxy {\r\n /**\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\n constructor(executor, onNoObservers) {\r\n this.observers = [];\r\n this.unsubscribes = [];\r\n this.observerCount = 0;\r\n // Micro-task scheduling by calling task.then().\r\n this.task = Promise.resolve();\r\n this.finalized = false;\r\n this.onNoObservers = onNoObservers;\r\n // Call the executor asynchronously so subscribers that are called\r\n // synchronously after the creation of the subscribe function\r\n // can still receive the very first value generated in the executor.\r\n this.task\r\n .then(() => {\r\n executor(this);\r\n })\r\n .catch(e => {\r\n this.error(e);\r\n });\r\n }\r\n next(value) {\r\n this.forEachObserver((observer) => {\r\n observer.next(value);\r\n });\r\n }\r\n error(error) {\r\n this.forEachObserver((observer) => {\r\n observer.error(error);\r\n });\r\n this.close(error);\r\n }\r\n complete() {\r\n this.forEachObserver((observer) => {\r\n observer.complete();\r\n });\r\n this.close();\r\n }\r\n /**\r\n * Subscribe function that can be used to add an Observer to the fan-out list.\r\n *\r\n * - We require that no event is sent to a subscriber sychronously to their\r\n * call to subscribe().\r\n */\r\n subscribe(nextOrObserver, error, complete) {\r\n let observer;\r\n if (nextOrObserver === undefined &&\r\n error === undefined &&\r\n complete === undefined) {\r\n throw new Error('Missing Observer.');\r\n }\r\n // Assemble an Observer object when passed as callback functions.\r\n if (implementsAnyMethods(nextOrObserver, [\r\n 'next',\r\n 'error',\r\n 'complete'\r\n ])) {\r\n observer = nextOrObserver;\r\n }\r\n else {\r\n observer = {\r\n next: nextOrObserver,\r\n error,\r\n complete\r\n };\r\n }\r\n if (observer.next === undefined) {\r\n observer.next = noop;\r\n }\r\n if (observer.error === undefined) {\r\n observer.error = noop;\r\n }\r\n if (observer.complete === undefined) {\r\n observer.complete = noop;\r\n }\r\n const unsub = this.unsubscribeOne.bind(this, this.observers.length);\r\n // Attempt to subscribe to a terminated Observable - we\r\n // just respond to the Observer with the final error or complete\r\n // event.\r\n if (this.finalized) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n try {\r\n if (this.finalError) {\r\n observer.error(this.finalError);\r\n }\r\n else {\r\n observer.complete();\r\n }\r\n }\r\n catch (e) {\r\n // nothing\r\n }\r\n return;\r\n });\r\n }\r\n this.observers.push(observer);\r\n return unsub;\r\n }\r\n // Unsubscribe is synchronous - we guarantee that no events are sent to\r\n // any unsubscribed Observer.\r\n unsubscribeOne(i) {\r\n if (this.observers === undefined || this.observers[i] === undefined) {\r\n return;\r\n }\r\n delete this.observers[i];\r\n this.observerCount -= 1;\r\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\r\n this.onNoObservers(this);\r\n }\r\n }\r\n forEachObserver(fn) {\r\n if (this.finalized) {\r\n // Already closed by previous event....just eat the additional values.\r\n return;\r\n }\r\n // Since sendOne calls asynchronously - there is no chance that\r\n // this.observers will become undefined.\r\n for (let i = 0; i < this.observers.length; i++) {\r\n this.sendOne(i, fn);\r\n }\r\n }\r\n // Call the Observer via one of it's callback function. We are careful to\r\n // confirm that the observe has not been unsubscribed since this asynchronous\r\n // function had been queued.\r\n sendOne(i, fn) {\r\n // Execute the callback asynchronously\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n if (this.observers !== undefined && this.observers[i] !== undefined) {\r\n try {\r\n fn(this.observers[i]);\r\n }\r\n catch (e) {\r\n // Ignore exceptions raised in Observers or missing methods of an\r\n // Observer.\r\n // Log error to console. b/31404806\r\n if (typeof console !== 'undefined' && console.error) {\r\n console.error(e);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n close(err) {\r\n if (this.finalized) {\r\n return;\r\n }\r\n this.finalized = true;\r\n if (err !== undefined) {\r\n this.finalError = err;\r\n }\r\n // Proxy is no longer needed - garbage collect references\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n this.observers = undefined;\r\n this.onNoObservers = undefined;\r\n });\r\n }\r\n}\r\n/** Turn synchronous function into one called asynchronously. */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(fn, onError) {\r\n return (...args) => {\r\n Promise.resolve(true)\r\n .then(() => {\r\n fn(...args);\r\n })\r\n .catch((error) => {\r\n if (onError) {\r\n onError(error);\r\n }\r\n });\r\n };\r\n}\r\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n for (const method of methods) {\r\n if (method in obj && typeof obj[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction noop() {\r\n // do nothing\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Check to make sure the appropriate number of arguments are provided for a public function.\r\n * Throws an error if it fails.\r\n *\r\n * @param fnName The function name\r\n * @param minCount The minimum number of arguments to allow for the function call\r\n * @param maxCount The maximum number of argument to allow for the function call\r\n * @param argCount The actual number of arguments provided.\r\n */\r\nconst validateArgCount = function (fnName, minCount, maxCount, argCount) {\r\n let argError;\r\n if (argCount < minCount) {\r\n argError = 'at least ' + minCount;\r\n }\r\n else if (argCount > maxCount) {\r\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\r\n }\r\n if (argError) {\r\n const error = fnName +\r\n ' failed: Was called with ' +\r\n argCount +\r\n (argCount === 1 ? ' argument.' : ' arguments.') +\r\n ' Expects ' +\r\n argError +\r\n '.';\r\n throw new Error(error);\r\n }\r\n};\r\n/**\r\n * Generates a string to prefix an error message about failed argument validation\r\n *\r\n * @param fnName The function name\r\n * @param argName The name of the argument\r\n * @return The prefix to add to the error thrown for validation.\r\n */\r\nfunction errorPrefix(fnName, argName) {\r\n return `${fnName} failed: ${argName} argument `;\r\n}\r\n/**\r\n * @param fnName\r\n * @param argumentNumber\r\n * @param namespace\r\n * @param optional\r\n */\r\nfunction validateNamespace(fnName, namespace, optional) {\r\n if (optional && !namespace) {\r\n return;\r\n }\r\n if (typeof namespace !== 'string') {\r\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\r\n throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\r\n }\r\n}\r\nfunction validateCallback(fnName, argumentName, \r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\ncallback, optional) {\r\n if (optional && !callback) {\r\n return;\r\n }\r\n if (typeof callback !== 'function') {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\r\n }\r\n}\r\nfunction validateContextObject(fnName, argumentName, context, optional) {\r\n if (optional && !context) {\r\n return;\r\n }\r\n if (typeof context !== 'object' || context === null) {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\r\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\r\n// so it's been modified.\r\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\r\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\r\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\r\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\r\n// pair).\r\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\r\n/**\r\n * @param {string} str\r\n * @return {Array}\r\n */\r\nconst stringToByteArray = function (str) {\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n // Is this the lead surrogate in a surrogate pair?\r\n if (c >= 0xd800 && c <= 0xdbff) {\r\n const high = c - 0xd800; // the high 10 bits.\r\n i++;\r\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\r\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\r\n c = 0x10000 + (high << 10) + low;\r\n }\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if (c < 65536) {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Calculate length without actually converting; useful for doing cheaper validation.\r\n * @param {string} str\r\n * @return {number}\r\n */\r\nconst stringLength = function (str) {\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n const c = str.charCodeAt(i);\r\n if (c < 128) {\r\n p++;\r\n }\r\n else if (c < 2048) {\r\n p += 2;\r\n }\r\n else if (c >= 0xd800 && c <= 0xdbff) {\r\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\r\n p += 4;\r\n i++; // skip trail surrogate.\r\n }\r\n else {\r\n p += 3;\r\n }\r\n }\r\n return p;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Copied from https://stackoverflow.com/a/2117523\r\n * Generates a new uuid.\r\n * @public\r\n */\r\nconst uuidv4 = function () {\r\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\r\n const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;\r\n return v.toString(16);\r\n });\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The amount of milliseconds to exponentially increase.\r\n */\r\nconst DEFAULT_INTERVAL_MILLIS = 1000;\r\n/**\r\n * The factor to backoff by.\r\n * Should be a number greater than 1.\r\n */\r\nconst DEFAULT_BACKOFF_FACTOR = 2;\r\n/**\r\n * The maximum milliseconds to increase to.\r\n *\r\n *

Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n *

Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","import { PACKAGE_VERSION } from './version.js';\n\n// Name of this application, used in the User-Agent.\nexport const APP_NAME = 'TinodeWeb/' + (PACKAGE_VERSION || '0.21');\n\n// API key. Use https://github.com/tinode/chat/tree/master/keygen to generate your own\nexport const API_KEY = 'AQEAAAABAAD_rAp4DJh05a1HAwFT3A6K';\n\n// The array of possible hosts to connect to.\nexport const KNOWN_HOSTS = {hosted: 'web.tinode.co', local: 'localhost:6060'};\n\n// Default host name and port to connect to.\nexport const DEFAULT_HOST = KNOWN_HOSTS.hosted;\n\n// Enable console logging.\nexport const LOGGING_ENABLED = true;\n\n// Minimum time between two keypress notifications, milliseconds.\nexport const KEYPRESS_DELAY = 3_000;\n// Delay before sending a read notification, milliseconds.\nexport const READ_DELAY = 1_500;\n\n// The default shortest allowed tag length. Matches the value on the server.\nexport const MIN_TAG_LENGTH = 2;\n// The default greatest allowed tag length. Matches the value on the server.\nexport const MAX_TAG_LENGTH = 96;\n// The default maximum number of tags allowed. Matches the value on the server.\nexport const MAX_TAG_COUNT = 16;\n\n// Access mode for P2P subscriptions initiated by the current user.\nexport const DEFAULT_P2P_ACCESS_MODE = 'JRWPS';\n// Access mode for new group topics created by the current user.\nexport const NEW_GRP_ACCESS_MODE = 'JRWPSAO';\n// Access mode for a channel.\nexport const CHANNEL_ACCESS_MODE = 'JR';\n\n// Access mode for no access.\nexport const NO_ACCESS_MODE = 'N';\n\n// Mediaquery breakpoint between desktop and mobile, in px. Should match the value\n// in @media (max-size: 640px) in base.css\nexport const MEDIA_BREAKPOINT = 640;\n// Size of css 'rem' unit in pixels. Default 1rem = 10pt = 13px.\nexport const REM_SIZE = 13;\n\n// Size of the avatar image: when image dimensions are greater or the image is not square, it's resized to\n// a square of this size or less.\nexport const AVATAR_SIZE = 384;\n\n// Maximum size of an avatar in bytes for sending in-band. Bigger avatars will be sent out of band (as uploads).\nexport const MAX_AVATAR_BYTES = 4096;\n\n// Size of the broken_image shown in MessagesView\nexport const BROKEN_IMAGE_SIZE = 32;\n\n// Size of video preview when dimensions are missing.\nexport const NO_DIMENSIONS_VIDEO = 128;\n\n// Number of chat messages to fetch in one call.\nexport const MESSAGES_PAGE = 24;\n\n// Default maximum in-band (included directly into the message) attachment size which fits into\n// a message of 256K in size. Used when the server-provided value is unavailable. The actual\n// binary size of the attachment should be smaller due to base64 encoding expansion and some overhead,\n// for instance 1024 bytes.\n// Increase this limit to a greater value in production, if desired. Also increase\n// max_message_size in the server config.\nexport const MAX_INBAND_ATTACHMENT_SIZE = 262_144;\n\n// Default absolute maximum attachment size to be used with the server = 8MB.\n// Used when the server-provided value is unavailable. Increase to something like 100MB in production.\nexport const MAX_EXTERN_ATTACHMENT_SIZE = 1 << 23;\n\n// Maximum allowed linear dimension (pixels) of an image sent inline. Larger images will be shrunk\n// to make the larger dimension fit under this size. You may want to adjust it to 1600 or\n// 2400 for production.\nexport const MAX_IMAGE_DIM = 1024;\n\n// Linear dimensions of image preview: shrink image under this size for previews.\nexport const IMAGE_PREVIEW_DIM = 64;\n\n// Linear dimensions of video screencapture: shrink image under this size for previews.\nexport const VIDEO_PREVIEW_DIM = 96;\n\n// Linear dimensions of image thumbnail: shrink image under this size for thumbnails in reply quote previews.\nexport const IMAGE_THUMBNAIL_DIM = 36;\n// Width of video thumbnail: allow it to be wider, but not taller. Use IMAGE_THUMBNAIL_DIM for height.\nexport const VIDEO_THUMBNAIL_WIDTH = 48;\n\n// Maximum number of online users to be shown in a topic title bar. Others will be\n// hidden under \"+X more\"\nexport const MAX_ONLINE_IN_TOPIC = 4;\n\n// Maximum length of user name, topic title, and private comment.\nexport const MAX_TITLE_LENGTH = 60;\n// Maximum length of topic description.\nexport const MAX_TOPIC_DESCRIPTION_LENGTH = 360;\n// Maximum length of user name when displaying a video call.\nexport const MAX_PEER_TITLE_LENGTH = 20;\n\n// Length of message previews in chat list, in characters.\nexport const MESSAGE_PREVIEW_LENGTH = 80;\n\n// Length of a quote in quoted reply (for outgoing messages).\nexport const QUOTED_REPLY_LENGTH = 30;\n// Length of a preview of a forwarded message.\nexport const FORWARDED_PREVIEW_LENGTH = 84;\n// Length of preview for a message being edited.\nexport const EDIT_PREVIEW_LENGTH = 48;\n\n// Minimum duration of an audio recording in milliseconds (2 sec).\nexport const MIN_DURATION = 2_000;\n// Maximum duration of an audio recording in milliseconds (10 min).\nexport const MAX_DURATION = 600_000;\n\n// Link for \"Contact Us\".\nexport const LINK_CONTACT_US = 'mailto:support@tinode.co';\n\n// Link to Privacy Policy.\nexport const LINK_PRIVACY_POLICY = 'https://tinode.co/privacy.html';\n\n// Link to Terms of Service.\nexport const LINK_TERMS_OF_SERVICE = 'https://tinode.co/terms.html';\n\n","// Video call states.\nexport const CALL_STATE_NONE = 0;\nexport const CALL_STATE_OUTGOING_INITATED = 1;\nexport const CALL_STATE_INCOMING_RECEIVED = 2;\nexport const CALL_STATE_IN_PROGRESS = 3;\n\n// Video call message headers representing call state.\nexport const CALL_HEAD_STARTED = 'started';\n","// File and image helper functions.\n\n// Supported image MIME types and corresponding file extensions.\nexport const SUPPORTED_IMAGE_FORMATS = ['image/jpeg', 'image/gif', 'image/png', 'image/svg', 'image/svg+xml'];\nexport const MIME_EXTENSIONS = ['jpg', 'gif', 'png', 'svg', 'svg'];\n\n// Get an URL from a theCard photo: either create a data: URL or return reference URL.\nexport function makeImageUrl(photo) {\n if (photo && typeof photo == 'object') {\n if (photo.ref) {\n return photo.ref\n }\n if (photo.data && photo.type) {\n const mime = photo.type.startsWith('image/') ? photo.type : ('image/' + photo.type);\n return 'data:' + mime + ';base64,' + photo.data;\n }\n }\n return null;\n}\n\n// Calculate linear dimensions for scaling image down to fit under a certain size.\n// Returns an object which contains destination sizes, source sizes, and offsets\n// into source (when making square images).\nexport function fitImageSize(width, height, maxWidth, maxHeight, forceSquare) {\n // Sanitize input\n width = width | 0;\n height = height | 0;\n maxWidth = maxWidth | 0;\n maxHeight = maxHeight | 0;\n\n if (width <= 0 || height <= 0 || maxWidth <= 0 || maxHeight <= 0) {\n return null;\n }\n\n if (forceSquare) {\n maxWidth = maxHeight = Math.min(maxWidth, maxHeight);\n }\n\n const scale = Math.min(\n Math.min(width, maxWidth) / width,\n Math.min(height, maxHeight) / height\n );\n\n const size = {\n dstWidth: (width * scale) | 0,\n dstHeight: (height * scale) | 0,\n };\n\n if (forceSquare) {\n // Also calculate parameters for making the image square.\n size.dstWidth = size.dstHeight = Math.min(size.dstWidth, size.dstHeight);\n size.srcWidth = size.srcHeight = Math.min(width, height);\n size.xoffset = ((width - size.srcWidth) / 2) | 0;\n size.yoffset = ((height - size.srcWidth) / 2) | 0;\n } else {\n size.xoffset = size.yoffset = 0;\n size.srcWidth = width;\n size.srcHeight = height;\n }\n return size;\n}\n\n// Ensure file's extension matches mime content type\nexport function fileNameForMime(fname, mime) {\n const idx = SUPPORTED_IMAGE_FORMATS.indexOf(mime);\n if (idx < 0 || !fname) {\n // Unknown mime or empty name.\n return fname;\n }\n const ext = MIME_EXTENSIONS[idx];\n\n const at = fname.lastIndexOf('.');\n if (at >= 0) {\n fname = fname.substring(0, at);\n }\n return fname + '.' + ext;\n}\n\n// Scale uploaded image to fit under certain dimensions and byte size, optionally constraining to a square.\n// Returns a promise which is resolven on success or rejected on failure.\nexport function imageScaled(fileOrBlob, maxWidth, maxHeight, maxSize, forceSquare) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onerror = function(err) {\n reject(new Error(\"Image format unrecognized\"));\n }\n img.onload = async function() {\n // Once the image is loaded, the URL is no longer needed.\n URL.revokeObjectURL(img.src);\n\n // Calculate the desired image dimensions.\n const dim = fitImageSize(img.width, img.height, maxWidth, maxHeight, forceSquare);\n if (!dim) {\n reject(new Error(\"Invalid image\"));\n return;\n }\n let canvas = document.createElement('canvas');\n canvas.width = dim.dstWidth;\n canvas.height = dim.dstHeight;\n let ctx = canvas.getContext('2d');\n ctx.imageSmoothingEnabled = true;\n ctx.drawImage(img, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,\n 0, 0, dim.dstWidth, dim.dstHeight);\n\n const mime = SUPPORTED_IMAGE_FORMATS.includes(fileOrBlob.type) ? fileOrBlob.type : 'image/jpeg';\n // Generate blob to check size of the image.\n let blob = await new Promise(resolve => canvas.toBlob(resolve, mime));\n if (!blob) {\n reject(new Error(\"Unsupported image format\"));\n return;\n }\n // Ensure the image is not too large. Shrink the image keeping the aspect ratio.\n // Do nothing if maxsize is <= 0.\n while (maxSize > 0 && blob.length > maxSize) {\n dim.dstWidth = (dim.dstWidth * 0.70710678118) | 0;\n dim.dstHeight = (dim.dstHeight * 0.70710678118) | 0;\n canvas.width = dim.dstWidth;\n canvas.height = dim.dstHeight;\n ctx = canvas.getContext('2d');\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.drawImage(img, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,\n 0, 0, dim.dstWidth, dim.dstHeight);\n blob = await new Promise(resolve => canvas.toBlob(resolve, mime));\n }\n\n canvas = null;\n resolve({mime: mime, blob: blob, width: dim.dstWidth, height: dim.dstHeight, name: fileNameForMime(fileOrBlob.name, mime)});\n };\n img.src = URL.createObjectURL(fileOrBlob);\n });\n}\n\n// Scale and crop image according to specified dimensions.\n// The coordinates are in unscaled image pixels, i.e. cut the rectangle first then scale it.\n// returns a promise.\nexport function imageCrop(mime, objURL, left, top, width, height, scale) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onerror = _ => {\n reject(new Error(\"Image format unrecognized\"));\n };\n img.onload = _ => {\n // Once the image is loaded, the URL is no longer needed.\n URL.revokeObjectURL(img.src);\n\n let canvas = document.createElement('canvas');\n canvas.width = width * scale;\n canvas.height = height * scale;\n let ctx = canvas.getContext('2d');\n ctx.imageSmoothingEnabled = true;\n ctx.drawImage(img, left, top, width, height, 0, 0, canvas.width, canvas.height);\n\n mime = SUPPORTED_IMAGE_FORMATS.includes(mime) ? mime : 'image/jpeg';\n // Generate blob to check size of the image.\n canvas.toBlob((blob) => {\n // Allow GC.\n canvas = null;\n if (blob) {\n resolve({mime: mime, blob: blob, width: width, height: height});\n } else {\n reject(new Error(\"Unsupported image format\"));\n }\n }, mime);\n };\n img.src = objURL;\n });\n}\n\n// Convert file to base64 string.\nexport function fileToBase64(file) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = _ => {\n reject(reader.error);\n };\n reader.onload = _ => {\n resolve({mime: file.type, bits: reader.result.split(',')[1], name: file.name});\n };\n reader.readAsDataURL(file);\n });\n}\n\n// Convert Blob to base64 string. Returns a promise resolved with the base64 string and mime.\nexport function blobToBase64(blob) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = _ => {\n reject(reader.error);\n };\n reader.onload = _ => {\n resolve({mime: blob.type, bits: reader.result.split(',')[1]});\n };\n reader.readAsDataURL(blob);\n });\n}\n\n// File pasted from the clipboard. It's either an inline image or a file attachment.\nexport function filePasted(event, onImageSuccess, onAttachmentSuccess, onError) {\n const items = (event.clipboardData || event.originalEvent.clipboardData || {}).items;\n if (!items || !items.length) {\n return false;\n }\n\n for (let i in items) {\n const item = items[i];\n if (item.kind === 'file') {\n const file = item.getAsFile();\n if (!file) {\n console.error(\"Failed to get file object from pasted file item\", item.kind, item.type);\n onError(\"Failed to get file object from pasted file item\");\n continue;\n }\n if (file.type && file.type.split('/')[0] == 'image') {\n onImageSuccess(file);\n } else {\n onAttachmentSuccess(file);\n }\n // Indicate that the pasted data contains a file.\n return true;\n }\n }\n // No file found.\n return false;\n}\n\n// Get mime type from data URL header.\nexport function getMimeType(header) {\n const mime = /^data:(image\\/[-+a-z0-9.]+);base64/.exec(header);\n return (mime && mime.length > 1) ? mime[1] : null;\n}\n\n// Given length of a binary object in bytes, calculate the length after\n// base64 encoding.\nexport function base64EncodedLen(n) {\n return Math.floor((n + 2) / 3) * 4;\n}\n\n// Given length of a base64-encoded object, calculate decoded size of the\n// pbject in bytes.\nexport function base64DecodedLen(n) {\n return Math.floor(n / 4) * 3;\n}\n\n// Re-encode string to standard base64 encoding with padding.\n// The string may be base64-URL encoded without the padding.\nexport function base64ReEncode(str) {\n if (str) {\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n try {\n str = btoa(atob(str));\n } catch(err) {\n console.error(\"Failed to base64 re-encode string.\", err);\n str = null;\n }\n }\n return str;\n}\n\n// Convert a base64 encoded string with the provided mime type into a Blob.\nexport function base64ToBlob(str, mime) {\n if (!str) {\n return null;\n }\n\n try {\n // Make blob.\n const bin = atob(str);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return new Blob([buf], { type: mime });\n } catch(err) {\n console.error(\"Failed to convert base64 to blob: \", err);\n }\n\n return null;\n}\n\nexport function intArrayToBase64(arr) {\n if (!Array.isArray(arr)) {\n return null;\n }\n try {\n let bin = '';\n new Uint8Array(arr).forEach(b => bin += String.fromCharCode(b));\n return window.btoa(bin);\n } catch (err) {}\n return null;\n}\n\nexport function base64ToIntArray(b64) {\n const arr = [];\n try {\n const bin = window.atob(b64);\n [...bin].forEach(c => {\n arr.push(c.charCodeAt(0));\n });\n return arr;\n } catch (err) {}\n return null;\n}\n","import React from 'react';\nimport { defineMessages } from 'react-intl';\n\nimport { Drafty } from 'tinode-sdk';\n\nimport AudioPlayer from '../widgets/audio-player.jsx'\nimport CallMessage from '../widgets/call-message.jsx'\nimport CallStatus from '../widgets/call-status.jsx';\nimport InlineVideo from '../widgets/inline-video.jsx';\nimport LazyImage from '../widgets/lazy-image.jsx'\nimport UploadingImage from '../widgets/uploading-image.jsx'\n\nimport { BROKEN_IMAGE_SIZE, IMAGE_THUMBNAIL_DIM, NO_DIMENSIONS_VIDEO, REM_SIZE, VIDEO_THUMBNAIL_WIDTH } from '../config.js';\nimport { base64ToBlob, blobToBase64, fitImageSize, imageScaled } from './blob-helpers.js';\nimport { idToColorClass, secondsToTime, shortenFileName } from './strformat.js';\nimport { cancelablePromise, sanitizeUrlForMime } from './utils.js';\n\nconst messages = defineMessages({\n drafty_form: {\n id: 'drafty_form',\n defaultMessage: 'Form: ',\n description: 'Comment for form in Drafty'\n },\n drafty_attachment: {\n id: 'drafty_attachment',\n defaultMessage: 'Attachment',\n description: 'Comment for attachment in Drafty'\n },\n drafty_image: {\n id: 'drafty_image',\n defaultMessage: 'Picture',\n description: 'Comment for embedded images in Drafty'\n },\n drafty_video: {\n id: 'drafty_video',\n defaultMessage: 'Video recording',\n description: 'Comment for videos embedded in Drafty'\n },\n drafty_unknown: {\n id: 'drafty_unknown',\n defaultMessage: 'Unsupported',\n description: 'Unsupported entity in drafty'\n }\n});\n\n// The main Drafty formatter: converts Drafty elements into React classes. 'this' is set by the caller.\n// 'this' must contain:\n// viewportWidth:\n// authorizeURL:\n// onImagePreview:\n// onVideoPreview:\n// onFormButtonClick:\n// onQuoteClick:\nexport function fullFormatter(style, data, values, key, stack) {\n if (stack.includes('QQ')) {\n return quoteFormatter.call(this, style, data, values, key);\n }\n\n if (!style) {\n // Unformatted.\n return values;\n }\n\n let el = Drafty.tagName(style);\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch (style) {\n case 'AU':\n // Show audio player.\n if (attr.src) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'audio'));\n attr.duration = data.duration > 0 ? (data.duration | 0) : undefined;\n attr.preview = data.preview;\n attr.loading = 'lazy';\n }\n el = AudioPlayer;\n // Audio element cannot have content.\n values = null;\n break;\n case 'BR':\n values = null;\n break;\n case 'EX':\n // Ignore.\n break;\n case 'HL':\n // Highlighted text. Assign class name.\n attr.className = 'highlight';\n break;\n case 'HD':\n el = null;\n values = null;\n break;\n case 'IM':\n // Additional processing for images\n el = handleImageData.call(this, el, data, attr);\n // Image element cannot have content.\n values = null;\n break;\n case 'BN':\n // Button\n attr.onClick = this.onFormButtonClick;\n let inner = React.Children.map(values, (child) => {\n return typeof child == 'string' ? child : undefined;\n });\n if (!inner || inner.length == 0) {\n inner = [attr.name]\n }\n // Get text which will be sent back when the button is clicked.\n attr['data-title'] = inner.join('');\n break;\n case 'MN':\n // Mention\n attr.className = 'mention'\n if (data) {\n attr.className += ' ' + idToColorClass(data.val, false, true);\n }\n break;\n case 'FM':\n // Form\n attr.className = 'bot-form';\n break;\n case 'RW':\n // Form element formatting is dependent on element content.\n break;\n case 'QQ':\n // Quote/citation.\n attr.className = 'reply-quote'\n attr.onClick = this.onQuoteClick;\n break;\n case 'VC':\n el = CallMessage;\n // Video call messages do not have content.\n values = null;\n if (data) {\n attr.callState = data.state;\n attr.incoming = data.incoming;\n attr.duration = data.duration;\n }\n break;\n case 'VD':\n // Additional processing for videos.\n el = handleVideoData.call(this, el, data, attr);\n // Video element cannot have content.\n values = null;\n break;\n default:\n if (!el) {\n // Unknown element.\n el = React.Fragment;\n attr = {key: key};\n // Generate comment for unknown element.\n let body = values;\n if (!Array.isArray(values) || !values.join('').trim()) {\n body = [{this.formatMessage(messages.drafty_unknown)}];\n }\n values = [extension, ' '].concat(body);\n }\n break;\n }\n if (!el) {\n return values;\n }\n return React.createElement(el, attr, values);\n}\n\n// Additional processing of image data.\nfunction handleImageData(el, data, attr) {\n if (!data) {\n attr.src = 'img/broken_image.png';\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n };\n return el;\n }\n\n attr.className = 'inline-image';\n const dim = fitImageSize(data.width, data.height,\n this.viewportWidth > 0 ? Math.min(this.viewportWidth - REM_SIZE * 6.5, REM_SIZE * 34.5) :\n REM_SIZE * 34.5, REM_SIZE * 24, false) ||\n {dstWidth: BROKEN_IMAGE_SIZE, dstHeight: BROKEN_IMAGE_SIZE};\n attr.style = {\n width: dim.dstWidth + 'px',\n height: dim.dstHeight + 'px',\n // Looks like a Chrome bug: broken image does not respect 'width' and 'height'.\n minWidth: dim.dstWidth + 'px',\n minHeight: dim.dstHeight + 'px'\n };\n if (!Drafty.isProcessing(data)) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'image'));\n attr.alt = data.name;\n if (attr.src) {\n if (Math.max(data.width || 0, data.height || 0) > IMAGE_THUMBNAIL_DIM) {\n // Allow previews for large enough images.\n attr.onClick = this.onImagePreview;\n attr.className += ' image-clickable';\n }\n attr.loading = 'lazy';\n } else {\n attr.src = null;\n }\n } else {\n // Use custom element instead of .\n el = UploadingImage;\n }\n\n return el;\n}\n\n// Additional processing of image data.\nfunction handleVideoData(el, data, attr) {\n if (!data) {\n attr.src = 'img/broken_video.png';\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n };\n return el;\n }\n attr.className = 'inline-image';\n const dim = fitImageSize(data.width, data.height,\n this.viewportWidth > 0 ? Math.min(this.viewportWidth - REM_SIZE * 6.5, REM_SIZE * 34.5) :\n REM_SIZE * 34.5, REM_SIZE * 24, false) ||\n {dstWidth: NO_DIMENSIONS_VIDEO, dstHeight: NO_DIMENSIONS_VIDEO};\n attr.style = {\n width: dim.dstWidth + 'px',\n height: dim.dstHeight + 'px',\n // Looks like a Chrome bug: broken image does not respect 'width' and 'height'.\n minWidth: dim.dstWidth + 'px',\n minHeight: dim.dstHeight + 'px'\n };\n if (!Drafty.isProcessing(data)) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'image'));\n attr.alt = data.name;\n if (data.ref || data.val) {\n attr.onClick = this.onVideoPreview;\n attr.loading = 'lazy';\n }\n el = InlineVideo;\n } else {\n // Use custom element instead of .\n el = UploadingImage;\n }\n\n return el;\n}\n\n// Converts Drafty object into a one-line preview. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\nexport function previewFormatter(style, data, values, key) {\n if (!style) {\n // Unformatted.\n return values;\n }\n\n let el = Drafty.tagName(style);\n const attr = { key: key };\n switch (style) {\n case 'AU':\n // Voicemail as '[mic] 0:00'.\n el = React.Fragment;\n values = [mic, ' ', secondsToTime(data.duration/1000)];\n break;\n case 'BR':\n // Replace new line with a space.\n el = React.Fragment;\n values = [' '];\n break;\n case 'HL':\n // Make highlight less prominent in preview.\n attr.className = 'highlight preview';\n break;\n case 'LN':\n case 'MN':\n // Disable links in previews.\n el = 'span';\n break;\n case 'IM':\n // Replace image with '[icon] Image'.\n el = React.Fragment;\n values = [photo, ' ', this.formatMessage(messages.drafty_image)];\n break;\n case 'BN':\n el = 'span';\n attr.className = 'flat-button faux';\n break;\n case 'FM':\n el = React.Fragment;\n values = [dashboard,\n this.formatMessage(messages.drafty_form)].concat(' ', values || []);\n break;\n case 'RW':\n el = React.Fragment;\n break;\n case 'EX':\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment, ' ', this.formatMessage(messages.drafty_attachment)];\n break;\n case 'VC':\n el = CallStatus;\n if (data) {\n attr.callState = data.state;\n attr.incoming = data.incoming;\n attr.duration = data.duration;\n }\n values = null;\n break;\n case 'QQ':\n case 'HD':\n el = null;\n values = null;\n break;\n case 'VD':\n // Replace image with '[icon] Video'.\n el = React.Fragment;\n values = [play_circle_outline, ' ', this.formatMessage(messages.drafty_video)];\n break;\n default:\n if (!el) {\n // Unknown element.\n el = React.Fragment;\n values = [extension, ' ', this.formatMessage(messages.drafty_unknown)];\n }\n break;\n }\n if (!el) {\n return values;\n }\n return React.createElement(el, attr, values);\n};\n\n// Converts Drafty object into a quoted reply; 'this' is set by the caller.\nfunction inlineImageAttr(attr, data) {\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n maxWidth: IMAGE_THUMBNAIL_DIM + 'px',\n maxHeight: IMAGE_THUMBNAIL_DIM + 'px',\n }\n attr.className = 'inline-image';\n attr.alt = this.formatMessage(messages.drafty_image);\n if (!data) {\n attr.src = 'img/broken_image.png';\n } else {\n attr.src = attr.src || 'img/broken_image.png';\n }\n attr.title = attr.alt;\n return attr;\n}\n\n// Converts Drafty object into a quoted reply; 'this' is set by the caller.\nfunction inlineVideoAttr(attr, data) {\n const dim = fitImageSize(data.width, data.height, VIDEO_THUMBNAIL_WIDTH, IMAGE_THUMBNAIL_DIM);\n attr.style = {\n width: dim.width + 'px',\n height: dim.height + 'px',\n maxWidth: VIDEO_THUMBNAIL_WIDTH + 'px',\n maxHeight: IMAGE_THUMBNAIL_DIM + 'px',\n }\n attr.className = 'inline-image';\n attr.alt = this.formatMessage(messages.drafty_video);\n attr.title = attr.alt;\n if (!data) {\n attr.src = 'img/broken_video.png';\n } else {\n attr.src = attr.src || 'img/broken_video.png';\n }\n return attr;\n}\n\n// Displays a portion of Drafty within 'QQ' quotes. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\n// authorizeURL: this.props.tinode.authorizeURL\n// onQuoteClick: this.handleQuoteClick (optional)\nfunction quoteFormatter(style, data, values, key) {\n if (['BR', 'EX', 'IM', 'MN', 'VD'].includes(style)) {\n let el = Drafty.tagName(style);\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch(style) {\n case 'BR':\n values = null;\n break;\n case 'IM':\n attr = inlineImageAttr.call(this, attr, data);\n values = [React.createElement('img', attr, null), ' ', attr.alt];\n el = React.Fragment;\n // Fragment attributes.\n attr = {key: key};\n break;\n case 'VD':\n attr = inlineVideoAttr.call(this, attr, data);\n values = [React.createElement('img', attr, null), ' ', attr.alt];\n el = React.Fragment;\n // Fragment attributes.\n attr = {key: key};\n break;\n case 'MN':\n el = 'span';\n attr.className = 'mention'\n if (data) {\n attr.className += ' ' + idToColorClass(data.val, false, true);\n }\n break;\n case 'EX':\n let fname;\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n fname = data.name;\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment,\n shortenFileName(fname, 16) || this.formatMessage(messages.drafty_attachment)];\n break;\n }\n return React.createElement(el, attr, values);\n }\n return previewFormatter.call(this, style, data, values, key);\n}\n\n// Create image thumbnail suitable for inclusion in a quote.\nfunction quoteImageOrVideo(data, isVideo) {\n let promise;\n let bits, ref, mime;\n if (isVideo) {\n bits = data.preview;\n mime = data.premime || 'image/jpeg';\n ref = data.preref;\n } else {\n bits = data.val;\n mime = data.mime;\n ref = data.ref;\n }\n // Get the blob from the image data.\n if (bits) {\n const blob = base64ToBlob(bits, mime);\n if (!blob) {\n throw new Error(\"Invalid image\");\n }\n promise = Promise.resolve(blob);\n } else if (ref) {\n promise = fetch(this.authorizeURL(sanitizeUrlForMime(ref, 'image')))\n .then(evt => {\n if (evt.ok) {\n return evt.blob();\n } else {\n throw new Error(`Image fetch unsuccessful: ${evt.status} ${evt.statusText}`);\n }\n });\n } else {\n throw new Error(\"Missing image data\");\n }\n\n // Scale the blob.\n return promise\n .then(blob => {\n // If it's an image, cut the square from the center of the image and shrink it.\n // If it's a video, allow it to be rectantular.\n return imageScaled(blob, isVideo ? VIDEO_THUMBNAIL_WIDTH : IMAGE_THUMBNAIL_DIM, IMAGE_THUMBNAIL_DIM, -1, !isVideo)\n }).then(scaled => {\n if (isVideo) {\n data.premime = scaled.mime;\n } else {\n data.mime = scaled.mime;\n }\n data.size = scaled.blob.size;\n data.width = scaled.width;\n data.height = scaled.height;\n delete data.ref;\n delete data.preref;\n // Keeping the original file name, if provided: ex.data.name;\n\n data.src = URL.createObjectURL(scaled.blob);\n return blobToBase64(scaled.blob);\n }).then(b64 => {\n if (isVideo) {\n data.preview = b64.bits;\n } else {\n data.val = b64.bits;\n }\n return data;\n }).catch(err => {\n delete data.val;\n delete data.preview;\n delete data.src;\n data.width = IMAGE_THUMBNAIL_DIM;\n data.height = IMAGE_THUMBNAIL_DIM;\n // Rethrow.\n throw err;\n });\n}\n\n// Create a preview of a reply.\nexport function replyFormatter(style, data, values, key, stack) {\n if (style == 'IM' || style == 'VD') {\n const isImage = style == 'IM';\n const attr = isImage ? inlineImageAttr.call(this, {key: key}, data) :\n inlineVideoAttr.call(this, {key: key}, data);\n\n let loadedPromise;\n try {\n loadedPromise = cancelablePromise(quoteImageOrVideo.call(this, data, style == 'VD'));\n } catch (error) {\n console.warn(\"Failed to quote image:\", error.message);\n loadedPromise = cancelablePromise(error);\n }\n attr.whenDone = loadedPromise;\n values = [React.createElement(LazyImage, attr, null), ' ', attr.alt];\n return React.createElement(React.Fragment, {key: key}, values);\n } else if (style == 'QQ') {\n if (stack.includes('QQ')) {\n // Quote inside quote when forwarding a message.\n return React.createElement('span', {key: key},\n [format_quote, ' ']);\n }\n\n const attr = Drafty.attrValue('QQ', data) || {};\n attr.key = key;\n attr.className = 'reply-quote'\n return React.createElement(Drafty.tagName('QQ'), attr, values);\n }\n return quoteFormatter.call(this, style, data, values, key);\n}\n","import { KNOWN_HOSTS, DEFAULT_HOST } from '../config.js';\n\n// Detect server address from the URL\nexport function detectServerAddress() {\n let host = DEFAULT_HOST;\n if (typeof window.location == 'object') {\n if (window.location.protocol == 'file:' || window.location.hostname == 'localhost') {\n host = KNOWN_HOSTS.local;\n } else if (window.location.hostname) {\n host = window.location.hostname + (window.location.port ? ':' + window.location.port : '');\n }\n }\n return host;\n}\n\n// Detect if the page is served over HTTPS.\nexport function isSecureConnection() {\n if (typeof window.location == 'object') {\n return window.location.protocol == 'https:';\n }\n return false;\n}\n\nexport function isLocalHost() {\n if (typeof window.location == 'object') {\n return window.location.hostname == 'localhost';\n }\n return false;\n}\n","// Helper functions for storing values in localStorage.\n// By default localStorage can store only strings, not objects or other types.\n\nexport default class LocalStorageUtil {\n // Replace old object with the new one.\n static setObject(key, value) {\n localStorage.setItem(key, JSON.stringify(value));\n }\n\n // Get stored object.\n static getObject(key) {\n const value = localStorage.getItem(key);\n return value && JSON.parse(value);\n }\n\n // Partially or wholly update stored object.\n static updateObject(key, value) {\n const oldVal = this.getObject(key);\n this.setObject(key, Object.assign(oldVal || {}, value));\n }\n\n // Just a wrapper.\n static removeItem(key) {\n localStorage.removeItem(key);\n }\n}\n","// Utility class for hash navigation.\n\nexport default class HashNavigation {\n // Parse hash as in http://www.example.com/path#hash as if it were\n // path and arguments.\n static parseUrlHash(hash) {\n // Split path from args, path -> parts[0], args->path[1]\n const parts = hash.split('?', 2);\n const params = {};\n let path = [];\n if (parts[0]) {\n path = parts[0].replace('#', '').split('/');\n }\n if (parts[1]) {\n parts[1].split('&').forEach((arg) => {\n // Can't use split() because the value may contain '='.\n const eq = arg.indexOf('=');\n if (eq > 0) {\n params[arg.slice(0, eq)] = decodeURIComponent(arg.slice(eq + 1));\n }\n });\n }\n return {path: path, params: params};\n }\n\n static navigateTo(url) {\n window.location.hash = url;\n }\n\n static composeUrlHash(path, params) {\n let url = path.join('/');\n const args = [];\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n args.push(key + '=' + encodeURIComponent(params[key]));\n }\n }\n if (args.length > 0) {\n url += '?' + args.join('&');\n }\n return url;\n }\n\n static addUrlParam(hash, key, value) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.params[key] = value;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static removeUrlParam(hash, key) {\n const parsed = HashNavigation.parseUrlHash(hash);\n delete parsed.params[key];\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlSidePanel(hash, sidepanel) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.path[0] = sidepanel;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlInfoPanel(hash, infopanel) {\n const parsed = HashNavigation.parseUrlHash(hash);\n if (infopanel) {\n parsed.params.info = infopanel;\n } else {\n delete parsed.params.info;\n }\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlTopic(hash, topic) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.path[1] = topic;\n // Close InfoView on topic change.\n delete parsed.params.info;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n}\n","// Short representation of time in the past.\nexport function shortDateFormat(then, locale) {\n locale = locale || window.navigator.userLanguage || window.navigator.language;\n const now = new Date();\n if (then.getFullYear() == now.getFullYear()) {\n // Same year.\n if (then.getMonth() == now.getMonth() && then.getDate() == now.getDate()) {\n // Same month and day, show time only.\n return then.toLocaleTimeString(locale, {hour12: false, hour: '2-digit', minute: '2-digit'});\n }\n // Different month and/or day, show month day, time.\n return then.toLocaleDateString(locale,\n {hour12: false, month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'});\n }\n // Different year: just show the date.\n return then.toLocaleDateString(locale, {year: 'numeric', month: 'short', day: 'numeric'});\n}\n\n// Representation a date relative to now.\nexport function relativeDateFormat(then, locale) {\n locale = locale || window.navigator.userLanguage || window.navigator.language;\n const now = new Date();\n const thenDays = Math.floor((then.getTime() - then.getTimezoneOffset() * 60_000) / 86_400_000);\n const nowDays = Math.floor((now.getTime() - now.getTimezoneOffset() * 60_000) / 86_400_000);\n const diff = thenDays - nowDays;\n if (Math.abs(diff) < 2) {\n // Today or yesterday.\n return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(diff, 'day')\n }\n // More than two days: just show the date.\n return new Intl.DateTimeFormat(locale).format(then);\n}\n\n// Convert seconds to [hours:]minutes:seconds, i.e. 156 sec -> 2:36, 3756 sec -> 1:02:36.\n// If fixedMins is true, then minutes are represented by at least two digits.\nexport function secondsToTime(seconds, fixedMin) {\n if (typeof seconds != 'number') {\n return '';\n }\n\n let min = (Math.floor(seconds / 60) | 0) % 60;\n let hours = Math.floor(seconds / 3600) | 0;\n\n if (fixedMin || hours > 0) {\n min = min < 10 ? `0${min}` : min;\n }\n let sec = (seconds | 0) % 60;\n sec = sec < 10 ? `0${sec}` : sec;\n if (hours == 0) {\n return `${min}:${sec}`;\n }\n return `${hours}:${min}:${sec}`;\n}\n\n// Convert a number of bytes to human-readable format.\nexport function bytesToHumanSize(bytes) {\n if (!bytes || bytes == 0) {\n return '0 Bytes';\n }\n\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];\n const bucket = Math.min(Math.floor(Math.log2(bytes) / 10) | 0, sizes.length-1);\n const count = bytes / Math.pow(1024, bucket);\n const round = bucket > 0 ? (count < 3 ? 2 : (count < 30 ? 1 : 0)) : 0;\n return count.toFixed(round) + ' ' + sizes[bucket];\n}\n\n// Shorten a file name to be under maxLength by clipping out the middle.\nexport function shortenFileName(filename, maxLength) {\n if (typeof filename != 'string') {\n return filename;\n }\n return filename.length > maxLength ?\n filename.slice(0, maxLength/2 - 1) + '…' + filename.slice(1 - maxLength/2) : filename;\n}\n\n// Get 32 bit integer hash value for a string. Ideally it should produce the same value\n// as Java's String#hash().\nfunction stringToColorHash(value) {\n let hash = 0;\n value = '' + value;\n for (let i = 0; i < value.length; i++) {\n hash = ((hash << 5) - hash) + value.charCodeAt(i);\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n}\n\n// User avatar letter color id.\nexport function letterTileColorId(userId) {\n return Math.abs(stringToColorHash(userId)) % 16;\n}\n\n// Converts user or topic ID to a CSS color class. Ideally it should produce the same color value as Java version.\n// params:\n// - {string} id: user or topic ID\n// - {boolean} light: light or dark version of the color.\n// - {boolean} fg: foreground (text) or background color.\nexport function idToColorClass(id, light, fg) {\n return (light ? 'lt-' : 'dk-') + (fg ? 'fg-' : 'bg-') + letterTileColorId(id);\n}\n\n// Takes ISO Alpha-2 country code, like 'US' and converts it to a flag emoji.\nexport function flagEmoji(countryCode) {\n const codePoints = countryCode\n .toUpperCase()\n .split('')\n .map(char => 0x1F1A5 + char.charCodeAt());\n return String.fromCodePoint(...codePoints);\n}\n","// Odds and ends\n\nimport { Tinode } from 'tinode-sdk';\n\n// Make shortcut icon appear with a green dot + show unread count in title.\nexport function updateFavicon(count) {\n const oldIcon = document.getElementById('shortcut-icon');\n const head = document.head || document.getElementsByTagName('head')[0];\n const newIcon = document.createElement('link');\n newIcon.type = 'image/png';\n newIcon.id = 'shortcut-icon';\n newIcon.rel = 'shortcut icon';\n newIcon.href = 'img/logo32x32' + (count > 0 ? 'a' : '') + '.png';\n if (oldIcon) {\n head.removeChild(oldIcon);\n }\n head.appendChild(newIcon);\n\n document.title = (count > 0 ? '('+count+') ' : '') + 'Tinode';\n}\n\n// Create theCard which represents user's or topic's \"public\" info.\nexport function theCard(fn, imageUrl, imageMimeType, note) {\n let card = null;\n fn = fn && fn.trim();\n note = note && note.trim();\n\n if (fn) {\n card = {\n fn: fn\n };\n }\n\n if (typeof note == 'string') {\n card = card || {};\n card.note = note ? note : Tinode.DEL_CHAR;\n }\n\n if (imageUrl) {\n card = card || {};\n let mimeType = imageMimeType;\n // Is this a data URL \"data:[][;base64],\"?\n const matches = /^data:(image\\/[-a-z0-9+.]+)?(;base64)?,/i.exec(imageUrl);\n if (matches) {\n mimeType = matches[1];\n card.photo = {\n data: imageUrl.substring(imageUrl.indexOf(',') + 1),\n ref: Tinode.DEL_CHAR\n };\n } else {\n card.photo = {\n data: Tinode.DEL_CHAR,\n ref: imageUrl\n };\n }\n card.photo.type = (mimeType || 'image/jpeg').substring('image/'.length);\n }\n\n return card;\n}\n\n// Deep-shallow compare two arrays: shallow compare each element.\nexport function arrayEqual(a, b) {\n if (a === b) {\n return true;\n }\n\n if (!Array.isArray(a) || !Array.isArray(b)) {\n return false;\n }\n\n // Compare lengths first.\n if (a.length != b.length) {\n return false;\n }\n // Order of elements is ignored.\n a.sort();\n b.sort();\n for (let i = 0, l = a.length; i < l; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\n// Checks (loosely) if the given string is a phone. If so, returns the phone number in a format\n// as close to E.164 as possible.\nexport function asPhone(val) {\n val = val.trim();\n if (/^(?:\\+?(\\d{1,3}))?[- (.]*(\\d{3})[- ).]*(\\d{3})[- .]*(\\d{2})[- .]*(\\d{2})?$/.test(val)) {\n return val.replace(/[- ().]*/, '');\n }\n return null;\n}\n\n// Checks (loosely) if the given string is an email. If so returns the email.\nexport function asEmail(val) {\n val = val.trim();\n if (/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$/.test(val)) {\n return val;\n }\n return null;\n}\n\n// Checks if URL is a relative url, i.e. has no 'scheme://', including the case of missing scheme '//'.\n// The scheme is expected to be RFC-compliant, e.g. [a-z][a-z0-9+.-]*\n// example.html - ok\n// https:example.com - not ok.\n// http:/example.com - not ok.\n// ' ↲ https://example.com' - not ok. (↲ means carriage return)\nexport function isUrlRelative(url) {\n return url && !/^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/im.test(url);\n}\n\n// Ensure URL does not present an XSS risk. Optional allowedSchemes may contain an array of\n// strings with permitted URL schemes, such as ['ftp', 'ftps']; otherwise accept http and https only.\nexport function sanitizeUrl(url, allowedSchemes) {\n if (typeof url != 'string') {\n return url;\n }\n\n // Strip control characters and whitespace. They are not valid URL characters anyway.\n url = url.replace(/[^\\x20-\\x7E]/gmi, '').trim();\n\n // Relative URLs are safe.\n // Relative URL does not start with ':', abcd123: or '//'.\n if (!/^([a-z][a-z0-9+.-]*:|\\/\\/)/i.test(url)) {\n return url;\n }\n\n // Blob URLs are safe.\n if (/^blob:http/.test(url)) {\n return url;\n }\n\n // Absolute URL. Accept only safe schemes, or no scheme.\n const schemes = Array.isArray(allowedSchemes) ? allowedSchemes.join('|') : 'http|https';\n const re = new RegExp('^((' + schemes + '):|//)', 'i');\n if (!re.test(url)) {\n return null;\n }\n\n return url;\n}\n\n// Ensure URL is suitable as a source like field: the URL must be a relative URL or\n// have http:, https:, blob: or data: scheme.\n// In case of data: scheme, the URL must must be of the right MIME type such as 'data:{mimeMajor}/XXXX;base64,'.\nexport function sanitizeUrlForMime(url, mimeMajor) {\n if (!url) {\n return null;\n }\n\n const sanitizedUrl = sanitizeUrl(url);\n if (sanitizedUrl) {\n return sanitizedUrl;\n }\n\n // Is this a data: URL of the appropriate mime type?\n const re = new RegExp(`data:${mimeMajor}\\/[a-z0-9.-]+;base64,`, 'i');\n if (re.test(url.trim())) {\n return url;\n }\n\n return null;\n}\n\n// Given message's received status, return name and color of a delivery indicator icon.\nexport function deliveryMarker(received) {\n switch (received) {\n case Tinode.MESSAGE_STATUS_SENDING:\n return { name: 'access_time' }; // watch face\n case Tinode.MESSAGE_STATUS_FAILED:\n case Tinode.MESSAGE_STATUS_FATAL:\n return { name: 'warning', color: 'danger-color' }; // yellow icon /!\\\n case Tinode.MESSAGE_STATUS_SENT:\n return { name: 'done' }; // checkmark\n case Tinode.MESSAGE_STATUS_RECEIVED:\n return { name: 'done_all' }; // double checkmark\n case Tinode.MESSAGE_STATUS_READ:\n return { name: 'done_all', color: 'blue' }; // blue double checkmark\n }\n return null;\n}\n\n// Wraps a promise to make it cancelable.\n// The parameter can be either a promise or an error. If it's an error, the wrapped promise is\n// created in a rejected state.\nexport function cancelablePromise(promise) {\n let hasCanceled = false;\n\n const wrappedPromise = promise instanceof Error ?\n Promise.reject(promise) :\n new Promise((resolve, reject) => {\n promise.then(\n result => hasCanceled ? reject({isCanceled: true}) : resolve(result),\n error => hasCanceled ? reject({isCanceled: true}) : reject(error)\n );\n });\n\n return {\n promise: wrappedPromise,\n cancel() {\n hasCanceled = true;\n },\n };\n};\n\n// Clips string to the specified length.\nexport function clipStr(str, length) {\n return str && str.substring(0, length);\n}\n","// This is a generated file. Don't edit.\n\nexport const PACKAGE_VERSION = \"0.23.0-rc1\";\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport CheckBox from '../widgets/checkbox.jsx';\n\nexport default class EditAccountView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleCheckboxClick = this.handleCheckboxClick.bind(this);\n }\n\n handleCheckboxClick(what, checked) {\n if (what == 'sound') {\n this.props.onToggleMessageSounds(checked);\n } else if (what == 'alert') {\n this.props.onTogglePushNotifications(checked);\n } else if (what == 'incognito') {\n this.props.onToggleIncognitoMode(checked);\n }\n }\n\n render() {\n return (\n

\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n );\n }\n};\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport InPlaceEdit from '../widgets/in-place-edit.jsx';\nimport PermissionsEditor from '../widgets/permissions-editor.jsx';\n\nconst messages = defineMessages({\n delete_account: {\n id: 'delete_account',\n defaultMessage: 'Delete account',\n description: 'Title for delete account warning'\n },\n delete_account_warning: {\n id: 'delete_account_warning',\n defaultMessage: 'Are you sure you want to delete your account? It cannot be undone.',\n description: 'Warning message when deleting an account'\n }\n});\n\nclass AccSecurityView extends React.Component {\n constructor(props) {\n super(props);\n\n const me = this.props.tinode.getMeTopic();\n let blockedCount = 0;\n me.contacts((c) => {\n if (c.acs && !c.acs.isJoiner()) {\n blockedCount ++;\n }\n });\n const defacs = me.getDefaultAccess();\n this.state = {\n auth: defacs ? defacs.auth : null,\n anon: defacs ? defacs.anon : null,\n showPermissionEditorFor: undefined,\n blockedCount: blockedCount,\n };\n\n this.handlePasswordUpdate = this.handlePasswordUpdate.bind(this);\n this.handleLaunchPermissionsEditor = this.handleLaunchPermissionsEditor.bind(this);\n this.handleHidePermissionsEditor = this.handleHidePermissionsEditor.bind(this);\n this.handlePermissionsChanged = this.handlePermissionsChanged.bind(this);\n this.handleDeleteAccount = this.handleDeleteAccount.bind(this);\n }\n\n handlePasswordUpdate(pwd) {\n this.setState({password: pwd});\n this.props.onUpdatePassword(pwd);\n }\n\n handleLaunchPermissionsEditor(which) {\n this.setState({\n showPermissionEditorFor: which,\n editedPermissions: this.state[which]\n });\n }\n\n handleHidePermissionsEditor() {\n this.setState({showPermissionEditorFor: undefined});\n }\n\n handlePermissionsChanged(perm) {\n let defacs = {};\n defacs[this.state.showPermissionEditorFor] = perm;\n this.props.onUpdateAccountDesc('me', undefined, undefined, defacs);\n\n let newState = {showPermissionEditorFor: undefined};\n newState[this.state.showPermissionEditorFor] = perm;\n this.setState(newState);\n }\n\n handleDeleteAccount(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(messages.delete_account), // title\n formatMessage(messages.delete_account_warning), // content\n (_ => this.props.onDeleteAccount()), // onConfirm\n null, // use default text \"OK\"\n true, // Show Reject button\n null // use default text \"Cancel\"\n );\n }\n\n render() {\n return (\n <>{this.state.showPermissionEditorFor ?\n \n :\n
\n
\n \n
\n {\n (password_unchanged) => \n }\n
\n
\n
\n \n
\n
\n
\n \n
\n
\n
Auth: {this.state.auth}
\n
Anon: {this.state.anon}
\n
\n
\n {this.state.blockedCount > 0 ?\n <>\n \n }\n );\n }\n};\n\nexport default injectIntl(AccSecurityView);\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport { APP_NAME, LINK_CONTACT_US, LINK_PRIVACY_POLICY, LINK_TERMS_OF_SERVICE } from '../config.js';\n\nexport default class AccSupportView extends React.PureComponent {\n render() {\n return (\n
\n \n
\n
\n
\n \n {APP_NAME}\n
\n
\n \n {Tinode.getLibrary()}\n
\n
\n \n {this.props.serverVersion}\n
\n
\n \n {this.props.serverAddress}\n
\n
\n
\n );\n }\n};\n","/* ContactsView holds all contacts-related stuff */\nimport React from 'react';\nimport { FormattedMessage, defineMessages } from 'react-intl';\n\nimport ContactList from '../widgets/contact-list.jsx';\n\nimport { updateFavicon } from '../lib/utils.js';\n\nconst messages = defineMessages({\n archived_contacts_title: {\n id: \"archived_contacts\",\n defaultMessage: \"Archived contacts ({count})\",\n description: \"Label for archived chats\"\n }\n});\n\nexport default class ContactsView extends React.Component {\n constructor(props) {\n super(props);\n\n this.handleAction = this.handleAction.bind(this);\n\n this.state = ContactsView.deriveStateFromProps(props);\n }\n\n static deriveStateFromProps(props) {\n const contacts = [];\n let unreadThreads = 0;\n let archivedCount = 0;\n props.chatList.forEach(c => {\n const blocked = c.acs && !c.acs.isJoiner();\n // Show only blocked contacts only when props.blocked == true.\n if (blocked && props.blocked) {\n contacts.push(c);\n }\n if (blocked || props.blocked) {\n return;\n }\n\n if (c.private && c.private.arch) {\n if (props.archive) {\n contacts.push(c);\n } else {\n archivedCount ++;\n }\n } else if (!props.archive) {\n contacts.push(c);\n unreadThreads += c.unread > 0 ? 1 : 0;\n }\n });\n\n contacts.sort((a, b) => {\n return (b.touched || 0) - (a.touched || 0);\n });\n\n if (archivedCount > 0) {\n contacts.push({\n action: 'archive',\n title: messages.archived_contacts_title,\n values: {count: archivedCount}\n });\n }\n\n return {\n contactList: contacts,\n unreadThreads: unreadThreads\n };\n }\n\n componentDidUpdate(prevProps, prevState) {\n if (prevProps.chatList != this.props.chatList ||\n prevProps.archive != this.props.archive ||\n prevProps.blocked != this.props.blocked) {\n const newState = ContactsView.deriveStateFromProps(this.props);\n this.setState(newState);\n if (newState.unreadThreads != prevState.unreadThreads) {\n updateFavicon(newState.unreadThreads);\n }\n }\n }\n\n handleAction(action_ignored) {\n this.props.onShowArchive();\n }\n\n render() {\n return (\n ¯∖_(ツ)_/¯\"\n description=\"HTML message shown in ContactList when no contacts are found\">{\n (no_contacts) => \n }\n );\n }\n};\n","// InfoView: panel with topic/user info.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport { AccessMode, Tinode } from 'tinode-sdk';\n\nimport AvatarUpload from '../widgets/avatar-upload.jsx';\nimport BadgeList from '../widgets/badge-list.jsx';\nimport CheckBox from '../widgets/checkbox.jsx';\nimport ContactList from '../widgets/contact-list.jsx';\nimport ErrorPanel from '../widgets/error-panel.jsx';\nimport GroupManager from '../widgets/group-manager.jsx';\nimport MenuCancel from '../widgets/menu-cancel.jsx';\nimport PermissionsEditor from '../widgets/permissions-editor.jsx';\nimport TopicCommonView from './topic-common-view.jsx';\nimport TopicSecurity from '../widgets/topic-security.jsx';\n\nimport { MAX_TITLE_LENGTH, MAX_TOPIC_DESCRIPTION_LENGTH, NO_ACCESS_MODE } from '../config.js';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\nimport { theCard, clipStr } from '../lib/utils.js';\n\nconst messages = defineMessages({\n info: {\n id: 'panel_title_info',\n description: 'Title for InfoView',\n defaultMessage: 'Info'\n },\n general: {\n id: 'panel_title_general',\n description: 'Title for TopicCommon.',\n defaultMessage: 'General'\n },\n security: {\n id: 'panel_title_security',\n description: 'Title for TopicSecirity and AccSecurity.',\n defaultMessage: 'Security'\n },\n members: {\n id: 'panel_title_members',\n description: 'Title for managing group members view.',\n defaultMessage: 'Members'\n },\n crop: {\n id: 'panel_title_crop',\n description: 'Title for AvatarCropView.',\n defaultMessage: 'Drag to Adjust'\n },\n perm_want: {\n id: 'requested_permissions',\n defaultMessage: 'Requested',\n description: 'Title for permissions'\n },\n perm_given: {\n id: 'granted_permissions',\n defaultMessage: 'Granted',\n description: 'Title for permissions'\n },\n perm_auth: {\n id: 'permissions_authenticated',\n defaultMessage: 'Authenticated',\n description: 'Title for editing default authenticated permissions'\n },\n perm_anon: {\n id: 'permissions_anonymous',\n defaultMessage: 'Anonymous',\n description: 'Title for editing default anonymous permissions'\n },\n perm_user: {\n id: 'permissions_user',\n defaultMessage: 'User\\'s Permissions',\n description: 'Title for editing user\\'s permissions'\n },\n edit_permissions: {\n id: 'menu_item_edit_permissions',\n defaultMessage: 'Edit permissions',\n description: 'Menu item [Edit permissions]'\n },\n});\n\nclass InfoView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n topic: null,\n owner: false,\n admin: false,\n sharer: false,\n deleter: false,\n muted: false,\n address: null,\n groupTopic: undefined,\n channel: undefined,\n fullName: undefined,\n description: undefined,\n avatar: null,\n private: null,\n selectedContact: null,\n access: null,\n modeGiven: null,\n modeWant: null,\n modeGiven2: null, // P2P topic, the other user mode given\n modeWant2: null, // P2P topic, the other user mode want\n auth: null,\n anon: null,\n contactList: [],\n trustedBadges: [],\n previousMetaDesc: undefined,\n previousSubsUpdated: undefined,\n };\n\n this.resetSubs = this.resetSubs.bind(this);\n this.resetDesc = this.resetDesc.bind(this);\n this.resetTags = this.resetTags.bind(this);\n this.onMetaDesc = this.onMetaDesc.bind(this);\n this.onSubsUpdated = this.onSubsUpdated.bind(this);\n this.handleImageChanged = this.handleImageChanged.bind(this);\n this.handleMuted = this.handleMuted.bind(this);\n this.handleUnarchive = this.handleUnarchive.bind(this);\n this.handlePermissionsChanged = this.handlePermissionsChanged.bind(this);\n this.handleLaunchPermissionsEditor = this.handleLaunchPermissionsEditor.bind(this);\n this.handleShowAddMembers = this.handleShowAddMembers.bind(this);\n this.handleMemberUpdateRequest = this.handleMemberUpdateRequest.bind(this);\n this.handleMemberSelected = this.handleMemberSelected.bind(this);\n this.handleContextMenu = this.handleContextMenu.bind(this);\n this.handleBackNavigate = this.handleBackNavigate.bind(this);\n }\n\n // No need to separately handle component mount.\n componentDidUpdate(props) {\n const topic = this.props.tinode.getTopic(props.topic);\n if (!topic) {\n return;\n }\n\n if (this.onMetaDesc != topic.onMetaDesc) {\n this.previousMetaDesc = topic.onMetaDesc;\n topic.onMetaDesc = this.onMetaDesc;\n\n this.previousSubsUpdated = topic.onSubsUpdated;\n topic.onSubsUpdated = this.onSubsUpdated;\n }\n\n if (this.state.topic != props.topic) {\n this.setState({topic: props.topic});\n this.resetDesc(topic, props);\n this.resetSubs(topic, props);\n this.resetTags(topic);\n }\n }\n\n componentWillUnmount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.setState({topic: null});\n topic.onMetaDesc = this.previousMetaDesc;\n topic.onSubsUpdated = this.previousSubsUpdated;\n }\n\n resetSubs(topic, props) {\n const newState = {contactList: []};\n if (topic.getType() == 'p2p') {\n // Fetch the other party in the p2p conversation.\n // Topic may not be ready yet, so check if user is found.\n const user2 = topic.subscriber(props.topic);\n if (user2) {\n newState.modeGiven2 = user2.acs.getGiven();\n newState.modeWant2 = user2.acs.getWant();\n } else {\n newState.modeGiven2 = NO_ACCESS_MODE;\n newState.modeWant2 = NO_ACCESS_MODE;\n }\n } else {\n topic.subscribers((sub) => {\n newState.contactList.push(sub);\n }, this);\n }\n\n this.setState(newState);\n }\n\n resetDesc(topic, props) {\n const defacs = topic.getDefaultAccess() || {};\n const acs = topic.getAccessMode();\n\n const badges = [];\n if (topic.trusted) {\n for (const [key, val] of Object.entries(topic.trusted)) {\n if (val) {\n badges.push(key);\n }\n }\n }\n\n this.setState({\n owner: acs && acs.isOwner(),\n admin: acs && acs.isAdmin(),\n sharer: acs && acs.isSharer(),\n deleter: acs && acs.isDeleter(),\n muted: acs && acs.isMuted(),\n\n fullName: clipStr(topic.public && topic.public.fn, MAX_TITLE_LENGTH),\n description: clipStr(topic.public && topic.public.note, MAX_TOPIC_DESCRIPTION_LENGTH),\n avatar: makeImageUrl(topic.public ? topic.public.photo : null),\n trustedBadges: badges,\n private: clipStr(topic.private && topic.private.comment, MAX_TITLE_LENGTH),\n archived: topic.isArchived(),\n address: topic.name,\n groupTopic: topic.isGroupType(),\n channel: topic.isChannelType() || topic.chan,\n access: acs ? acs.getMode() : undefined,\n modeGiven: acs ? acs.getGiven() : undefined,\n modeWant: acs ? acs.getWant() : undefined,\n auth: defacs.auth,\n anon: defacs.anon\n });\n }\n\n resetTags(topic) {\n if (topic.getType() != 'grp') {\n return;\n }\n\n const acs = topic.getAccessMode();\n if (acs && acs.isOwner()) {\n // Requesting tags: owner is editing the topic.\n topic.getMeta(topic.startMetaQuery().withTags().build());\n }\n }\n\n onMetaDesc(desc) {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.resetDesc(topic, this.props);\n\n if (this.previousMetaDesc && this.previousMetaDesc != this.onMetaDesc) {\n this.previousMetaDesc(desc);\n }\n }\n\n onSubsUpdated(subs) {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.resetSubs(topic, this.props);\n\n if (this.previousSubsUpdated && this.previousSubsUpdated != this.onSubsUpdated) {\n this.previousSubsUpdated(subs);\n }\n }\n\n handleImageChanged(mime, img) {\n this.setState({avatar: img});\n this.props.onTopicDescUpdate(this.props.topic, theCard(null, img || Tinode.DEL_CHAR), null);\n }\n\n handleMuted(ignored, checked) {\n this.setState({muted: checked});\n this.props.onChangePermissions(this.props.topic, checked ? '-P' : '+P');\n }\n\n handleUnarchive(ignored, ignored2) {\n this.props.onTopicUnArchive(this.props.topic);\n }\n\n handlePermissionsChanged(which, perm) {\n switch (which) {\n case 'auth':\n this.props.onTopicDescUpdateRequest(this.props.topic, null, null, {auth: perm});\n break;\n case 'anon':\n this.props.onTopicDescUpdateRequest(this.props.topic, null, null, {anon: perm});\n break;\n case 'mode':\n case 'want':\n this.props.onChangePermissions(this.props.topic, perm);\n break;\n case 'given':\n this.props.onChangePermissions(this.props.topic, perm, this.props.topic);\n break;\n case 'user':\n this.props.onChangePermissions(this.props.topic, perm, this.state.userPermissionsEdited);\n break;\n }\n\n this.handleBackNavigate();\n }\n\n handleLaunchPermissionsEditor(which, uid) {\n const {formatMessage} = this.props.intl;\n let toEdit, toCompare, toSkip, titleEdit, titleCompare, userTitle, userAvatar;\n switch (which) {\n case 'mode':\n toEdit = this.state.access;\n break;\n case 'want':\n toEdit = this.state.modeWant;\n toCompare = this.state.modeGiven;\n if (this.state.owner) {\n // Don't allow owner to unset 'O' permission. All other permissions are OK.\n toSkip = 'O';\n } else {\n // Allow accepting any of 'ASDO' permissions but don't allow asking for them.\n toSkip = AccessMode.encode(AccessMode.diff('ASDO', this.state.modeGiven));\n if (this.state.channel) {\n // Channels are read-only.\n toSkip += 'W';\n }\n }\n titleEdit = formatMessage(messages.perm_want);\n titleCompare = formatMessage(messages.perm_given);\n break;\n case 'given':\n toEdit = this.state.modeGiven2;\n toCompare = this.state.modeWant2;\n toSkip = this.state.groupTopic ? (this.state.owner ? '' : 'O') : 'ASDO';\n titleEdit = formatMessage(messages.perm_given);\n titleCompare = formatMessage(messages.perm_want);\n break;\n case 'auth':\n toEdit = this.state.auth;\n toSkip = 'O';\n break;\n case 'anon':\n toEdit = this.state.anon;\n toSkip = 'O';\n break;\n case 'user': {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n const user = topic.subscriber(uid);\n if (!user || !user.acs) {\n return;\n }\n toEdit = user.acs.getGiven();\n toCompare = user.acs.getWant();\n toSkip = this.state.owner ? '' : 'O';\n titleEdit = formatMessage(messages.perm_given);\n titleCompare = formatMessage(messages.perm_want);\n if (user.public) {\n userTitle = user.public.fn;\n userAvatar = user.public.photo;\n }\n break;\n }\n default:\n console.error(\"Unknown permission editing mode '\" + which + \"'\");\n return;\n }\n this.setState({\n userPermissionsEdited: uid,\n userPermissionsTitle: userTitle,\n userPermissionsAvatar: userAvatar,\n editedPermissions: toEdit,\n immutablePermissions: toCompare,\n editedPermissionsTitle: titleEdit,\n immutablePermissionsTitle: titleCompare,\n editedPermissionsSkipped: toSkip,\n });\n this.props.onNavigate(`perm/${which}`);\n }\n\n handleShowAddMembers(e) {\n e.preventDefault();\n this.props.onInitFind();\n this.props.onNavigate('members');\n }\n\n handleMemberUpdateRequest(members, added, removed) {\n this.props.onMemberUpdateRequest(this.props.topic, added, removed);\n this.props.onNavigate('info');\n }\n\n handleMemberSelected(uid) {\n this.setState({selectedContact: uid});\n }\n\n handleBackNavigate() {\n const args = (this.props.panel || 'info').split('/');\n if (args[0] == 'info') {\n this.props.onNavigate(null);\n } else if (args[0] == 'perm') {\n if (args[1] == 'user') {\n this.props.onNavigate('info');\n } else {\n this.props.onNavigate('security');\n }\n } else {\n this.props.onNavigate('info');\n }\n }\n\n handleContextMenu(params) {\n const {formatMessage} = this.props.intl;\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n const user = topic.subscriber(params.topicName);\n if (!user || !user.acs) {\n return;\n }\n\n const isMe = this.props.tinode.isMe(params.topicName);\n const menuItems = [{\n title: formatMessage(messages.edit_permissions),\n handler: _ => this.handleLaunchPermissionsEditor(isMe ? 'want' : 'user', params.topicName)\n }];\n if (!isMe) {\n menuItems.push('member_delete');\n }\n menuItems.push(user.acs.isMuted() ? 'member_unmute' : 'member_mute');\n if (!isMe) {\n menuItems.push(user.acs.isJoiner() ? 'member_block' : 'member_unblock');\n }\n this.props.showContextMenu({\n topicName: this.props.topic,\n x: params.x,\n y: params.y,\n user: params.topicName}, menuItems);\n }\n\n render() {\n const args = (this.props.panel || 'info').split('/');\n const view = args[0];\n args.shift();\n\n const {formatMessage} = this.props.intl;\n const panelTitle = formatMessage((view == 'perm' ? messages['perm_' + args[0]] : messages[view])\n || messages['info']);\n\n return (\n
\n
\n
{panelTitle}
\n
\n \n
\n
\n {this.props.displayMobile ?\n : null}\n {view == 'members' ?\n \n :\n view == 'perm' && args.length > 0 ?\n this.handlePermissionsChanged(args[0], mode)}\n onCancel={this.handleBackNavigate} />\n :\n view == 'general' ?\n \n :\n view == 'security' ?\n \n :\n
\n
\n {e.preventDefault(); this.props.onNavigate('general');}}>\n edit \n \n \n
\n \n
\n
\n
\n
{this.state.fullName}\n {this.state.channel ? \"channel\" : null}
\n
\n {this.state.private ?\n
\n
\n
{this.state.private}
\n
\n : null\n }\n
\n  \n {this.state.address}\n
\n
\n \n
\n {this.state.description ?\n
\n \n
{this.state.description}
\n
: null}\n
\n
\n
\n \n \n
\n {this.state.archived ?\n
\n \n \n
\n :\n null\n }\n
\n \n {this.state.groupTopic && this.state.sharer ?\n <>\n
\n
\n \n
\n \n {\n (no_members) => \n }\n \n :\n null\n }\n
\n }\n
\n );\n }\n};\n\nexport default injectIntl(InfoView);\n","// Login form.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport CheckBox from '../widgets/checkbox.jsx';\nimport VisiblePassword from '../widgets/visible-password.jsx';\n\nexport default class LoginView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n login: props.login,\n password: '',\n hostName: props.serverAddress,\n saveToken: props.persist\n };\n this.handleLoginChange = this.handleLoginChange.bind(this);\n this.handlePasswordChange = this.handlePasswordChange.bind(this);\n this.handleToggleSaveToken = this.handleToggleSaveToken.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n handleLoginChange(e) {\n this.setState({login: e.target.value});\n }\n\n handlePasswordChange(e) {\n this.setState({password: e.target.value});\n }\n\n handleToggleSaveToken() {\n this.props.onPersistenceChange(!this.state.saveToken);\n this.setState({saveToken: !this.state.saveToken});\n }\n\n handleSubmit(e) {\n e.preventDefault();\n this.props.onLogin(this.state.login.trim(), this.state.password.trim());\n }\n\n render() {\n let submitClasses = 'primary';\n if (this.props.disabled) {\n submitClasses += ' disabled';\n }\n\n return (\n
\n \n {\n (login_prompt) => \n }\n \n \n {\n (password_prompt) => \n }\n \n
\n \n \n \n \n \n
\n
\n \n
\n
\n );\n }\n};\n","/* This is just a static page to display when no conversation is selected. */\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport { APP_NAME } from '../config.js';\n\nexport default class LogoView extends React.PureComponent {\n render() {\n const version = APP_NAME + ' (' + Tinode.getLibrary() + ')';\n return (\n
\n
\n \n \"logo\"\n

Tinode Web

\n
\n

{version}

\n

{this.props.serverVersion} ({this.props.serverAddress})

\n
\n
\n );\n }\n};\n","// Panel with a chat.\n\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport { Drafty, Tinode } from 'tinode-sdk';\n\nimport CallPanel from '../widgets/call-panel.jsx';\nimport ChatMessage from '../widgets/chat-message.jsx';\nimport ContactBadges from '../widgets/contact-badges.jsx';\nimport DocPreview from '../widgets/doc-preview.jsx';\nimport ErrorPanel from '../widgets/error-panel.jsx';\nimport GroupSubs from '../widgets/group-subs.jsx';\nimport ImagePreview from '../widgets/image-preview.jsx';\nimport Invitation from '../widgets/invitation.jsx';\nimport LetterTile from '../widgets/letter-tile.jsx';\nimport LoadSpinner from '../widgets/load-spinner.jsx';\nimport LogoView from './logo-view.jsx';\nimport MetaMessage from '../widgets/meta-message.jsx';\nimport PinnedMessages from '../widgets/pinned-messages.jsx';\nimport SendMessage from '../widgets/send-message.jsx';\nimport VideoPreview from '../widgets/video-preview.jsx';\n\nimport { DEFAULT_P2P_ACCESS_MODE, EDIT_PREVIEW_LENGTH, IMAGE_PREVIEW_DIM, KEYPRESS_DELAY,\n MESSAGES_PAGE, MAX_EXTERN_ATTACHMENT_SIZE, MAX_IMAGE_DIM, MAX_INBAND_ATTACHMENT_SIZE,\n READ_DELAY, QUOTED_REPLY_LENGTH, VIDEO_PREVIEW_DIM } from '../config.js';\nimport { CALL_STATE_OUTGOING_INITATED, CALL_STATE_IN_PROGRESS } from '../constants.js';\nimport { blobToBase64, fileToBase64, imageScaled, makeImageUrl } from '../lib/blob-helpers.js';\nimport HashNavigation from '../lib/navigation.js';\nimport { bytesToHumanSize, relativeDateFormat, shortDateFormat } from '../lib/strformat.js';\n\n// Run timer with this frequency (ms) for checking notification queue.\nconst NOTIFICATION_EXEC_INTERVAL = 300;\n// Scroll distance before [go to latest message] button is shown.\nconst SHOW_GO_TO_LAST_DIST = 100;\n// Sctoll distance from the top when fetching the page of earlier messages is triggered.\nconst FETCH_PAGE_TRIGGER = 40;\n\nconst messages = defineMessages({\n online_now: {\n id: 'online_now',\n defaultMessage: 'online now',\n description: 'Indicator that the user or topic is currently online',\n },\n last_seen: {\n id: 'last_seen_timestamp',\n defaultMessage: 'Last seen',\n description: 'Label for the timestamp of when the user or topic was last online'\n },\n not_found: {\n id: 'title_not_found',\n defaultMessage: 'Not found',\n description: 'Title shown when topic is not found'\n },\n channel: {\n id: 'channel',\n defaultMessage: 'channel',\n description: 'Subtitle shown for channels in MessagesView instead of last seen'\n },\n file_attachment_too_large: {\n id: 'file_attachment_too_large',\n defaultMessage: 'The file size {size} exceeds the {limit} limit.',\n description: 'Error message when attachment is too large'\n },\n invalid_content: {\n id: 'invalid_content',\n defaultMessage: 'invalid content',\n description: 'Shown when the message is unreadable'\n },\n editing_message: {\n id: 'editing_message',\n defaultMessage: 'Editing',\n description: 'Title over message editing preview'\n },\n drag_file: {\n id: 'drag_file',\n defaultMessage: 'Drag file here',\n description: 'Prompt on the file drag-n-drop overlay banner'\n }\n});\n\n// Checks if the access permissions are granted but not yet accepted.\nfunction isUnconfirmed(acs) {\n if (acs) {\n const ex = acs.getExcessive() || '';\n return acs.isJoiner('given') && (ex.includes('R') || ex.includes('W'));\n }\n return false;\n}\n\nfunction isPeerRestricted(acs) {\n if (acs) {\n const ms = acs.getMissing() || '';\n return acs.isJoiner('want') && (ms.includes('R') || ms.includes('W'));\n }\n return false;\n}\n\nfunction shouldPresentCallPanel(callState) {\n // Show call panel if either:\n // - call is outgoing (and the client is waiting for the other side to pick up) or,\n // - call is already in progress.\n return callState == CALL_STATE_OUTGOING_INITATED || callState == CALL_STATE_IN_PROGRESS;\n}\n\nclass MessagesView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = MessagesView.getDerivedStateFromProps(props, {});\n\n this.leave = this.leave.bind(this);\n this.sendMessage = this.sendMessage.bind(this);\n this.retrySend = this.retrySend.bind(this);\n this.sendImageAttachment = this.sendImageAttachment.bind(this);\n this.sendVideoAttachment = this.sendVideoAttachment.bind(this);\n this.sendFileAttachment = this.sendFileAttachment.bind(this);\n this.sendAudioAttachment = this.sendAudioAttachment.bind(this);\n this.sendKeyPress = this.sendKeyPress.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.handleScrollReference = this.handleScrollReference.bind(this);\n this.mountDnDEvents = this.mountDnDEvents.bind(this);\n this.handleScrollEvent = this.handleScrollEvent.bind(this);\n this.handleDescChange = this.handleDescChange.bind(this);\n this.handleSubsUpdated = this.handleSubsUpdated.bind(this);\n this.handleMessageUpdate = this.handleMessageUpdate.bind(this);\n this.handleAuxUpdate = this.handleAuxUpdate.bind(this);\n this.handleAllMessagesReceived = this.handleAllMessagesReceived.bind(this);\n this.handleInfoReceipt = this.handleInfoReceipt.bind(this);\n this.handleExpandMedia = this.handleExpandMedia.bind(this);\n this.handleClosePreview = this.handleClosePreview.bind(this);\n this.handleFormResponse = this.handleFormResponse.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n this.handleShowMessageContextMenu = this.handleShowMessageContextMenu.bind(this);\n this.handleNewChatAcceptance = this.handleNewChatAcceptance.bind(this);\n this.handleEnablePeer = this.handleEnablePeer.bind(this);\n this.handleAttachFile = this.handleAttachFile.bind(this);\n this.handleAttachImageOrVideo = this.handleAttachImageOrVideo.bind(this);\n this.handleCancelUpload = this.handleCancelUpload.bind(this);\n this.postReadNotification = this.postReadNotification.bind(this);\n this.clearNotificationQueue = this.clearNotificationQueue.bind(this);\n this.goToLatestMessage = this.goToLatestMessage.bind(this);\n this.handleFileDrop = this.handleFileDrop.bind(this);\n\n this.handlePickReply = this.handlePickReply.bind(this);\n this.handleEditMessage = this.handleEditMessage.bind(this);\n this.handleCancelReply = this.handleCancelReply.bind(this);\n this.handleQuoteClick = this.handleQuoteClick.bind(this);\n this.handleUnpinMessage = this.handleUnpinMessage.bind(this);\n this.handleCallHangup = this.handleCallHangup.bind(this);\n\n this.isDragEnabled = this.isDragEnabled.bind(this);\n this.handleDragStart = this.handleDragStart.bind(this);\n this.handleDragIn = this.handleDragIn.bind(this);\n this.handleDragOut = this.handleDragOut.bind(this);\n this.handleDrag = this.handleDrag.bind(this);\n this.handleDrop = this.handleDrop.bind(this);\n\n this.chatMessageRefs = {};\n this.getOrCreateMessageRef = this.getOrCreateMessageRef.bind(this);\n\n // Keeps track of the drag event.\n // Need a counter b/c the browser's 'drag' events may fire multiple times\n // when the user takes the mouse pointer over the container:\n // for the component itself and for all nested/child elements.\n this.dragCounter = 0;\n this.dndRef = null;\n\n this.readNotificationQueue = [];\n this.readNotificationTimer = null;\n\n this.keyPressTimer = null;\n }\n\n getOrCreateMessageRef(seqId) {\n if (this.chatMessageRefs.hasOwnProperty(seqId)) {\n return this.chatMessageRefs[seqId];\n }\n const ref = React.createRef();\n this.chatMessageRefs[seqId] = ref;\n return ref;\n }\n\n componentDidMount() {\n if (this.messagesScroller) {\n this.messagesScroller.addEventListener('scroll', this.handleScrollEvent);\n }\n\n // Drag and drop events\n this.mountDnDEvents(this.dndRef);\n }\n\n componentWillUnmount() {\n if (this.messagesScroller) {\n this.messagesScroller.removeEventListener('scroll', this.handleScrollEvent);\n }\n\n // Flush all notifications.\n this.clearNotificationQueue();\n\n // Drag and drop events\n if (this.dndRef) {\n this.dndRef.removeEventListener('dragstart', this.handleDragStart);\n this.dndRef.removeEventListener('dragenter', this.handleDragIn);\n this.dndRef.removeEventListener('dragleave', this.handleDragOut);\n this.dndRef.removeEventListener('dragover', this.handleDrag);\n this.dndRef.removeEventListener('drop', this.handleDrop);\n }\n }\n\n // Scroll last message into view on component update e.g. on message received\n // or vertical shrinking.\n componentDidUpdate(prevProps, prevState) {\n if (this.messagesScroller &&\n (prevState.topic != this.state.topic || prevState.maxSeqId != this.state.maxSeqId ||\n prevState.minSeqId != this.state.minSeqId)) {\n // New message.\n if (this.state.scrollPosition < SHOW_GO_TO_LAST_DIST) {\n this.messagesScroller.scrollTop = this.messagesScroller.scrollHeight -\n this.state.scrollPosition - this.messagesScroller.offsetHeight;\n }\n }\n\n const topic = this.props.tinode ? this.props.tinode.getTopic(this.state.topic) : undefined;\n if (this.state.topic != prevState.topic) {\n if (prevState.topic && !Tinode.isNewGroupTopicName(prevState.topic)) {\n this.leave(prevState.topic);\n if (prevState.rtcPanel) {\n this.handleCallHangup(prevState.topic, prevProps.callSeq);\n }\n }\n\n if (topic) {\n topic.onData = this.handleMessageUpdate;\n topic.onAllMessagesReceived = this.handleAllMessagesReceived;\n topic.onInfo = this.handleInfoReceipt;\n topic.onMetaDesc = this.handleDescChange;\n topic.onSubsUpdated = this.handleSubsUpdated;\n topic.onPres = this.handleSubsUpdated;\n topic.onAuxUpdated = this.handleAuxUpdate;\n }\n }\n\n if (!this.props.applicationVisible) {\n // If application is not visible, flush all unsent 'read' notifications.\n this.clearNotificationQueue();\n } else {\n // Otherwise assume there are unread messages.\n this.postReadNotification(0);\n }\n\n if (topic && ((this.state.topic != prevState.topic) || !prevProps.ready)) {\n // Don't immediately subscribe to a new p2p topic, wait for the first message.\n if (topic._new && topic.isP2PType()) {\n topic.getMeta(topic.startMetaQuery().withDesc().build());\n } else {\n this.subscribe(topic);\n }\n }\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n let nextState = {};\n if (!nextProps.topic) {\n // Default state: no topic.\n nextState = {\n minSeqId: -1,\n maxSeqId: -1,\n latestClearId: -1,\n onlineSubs: [],\n topic: null,\n title: '',\n avatar: null,\n isVerified: false,\n isStaff: false,\n isDangerous: false,\n deleted: false,\n docPreview: null,\n imagePreview: null,\n imagePostview: null,\n videoPreview: null,\n videoPostview: null,\n rtcPanel: null,\n typingIndicator: false,\n scrollPosition: 0,\n fetchingMessages: false,\n peerMessagingDisabled: false,\n channel: false,\n reply: null,\n contentToEdit: null,\n showGoToLastButton: false,\n dragging: false,\n pins: [],\n selectedPin: 0\n };\n } else if (nextProps.topic != prevState.topic) {\n const topic = nextProps.tinode.getTopic(nextProps.topic);\n\n nextState = {\n topic: nextProps.topic,\n deleted: topic._deleted,\n docPreview: null,\n imagePreview: null,\n imagePostview: null,\n videoPreview: null,\n videoPostview: null,\n rtcPanel: null,\n typingIndicator: false,\n scrollPosition: 0,\n fetchingMessages: false,\n showGoToLastButton: false,\n contentToEdit: null,\n dragging: false,\n selectedPin: 0\n };\n\n if (nextProps.forwardMessage) {\n // We are forwarding a message. Show preview.\n nextState.reply = {\n content: nextProps.forwardMessage.preview,\n seq: null\n };\n } else {\n nextState.reply = null;\n }\n\n if (topic) {\n // Topic exists.\n const subs = [];\n\n if (nextProps.connected) {\n topic.subscribers((sub) => {\n if (sub.online && sub.user != nextProps.myUserId) {\n subs.push(sub);\n }\n });\n }\n\n Object.assign(nextState, {\n onlineSubs: subs\n });\n\n if (topic.public) {\n Object.assign(nextState, {\n title: topic.public.fn,\n avatar: makeImageUrl(topic.public.photo)\n });\n } else {\n Object.assign(nextState, {\n title: '',\n avatar: null\n });\n }\n\n const peer = topic.p2pPeerDesc();\n if (peer) {\n Object.assign(nextState, {\n peerMessagingDisabled: isPeerRestricted(peer.acs)\n });\n } else if (prevState.peerMessagingDisabled) {\n Object.assign(nextState, {\n peerMessagingDisabled: false\n });\n }\n Object.assign(nextState, {\n minSeqId: topic.minMsgSeq(),\n maxSeqId: topic.maxMsgSeq(),\n latestClearId: topic.maxClearId(),\n channel: topic.isChannelType(),\n pins: (topic.aux('pins') || []).slice()\n });\n\n if (nextProps.callTopic == topic.name && shouldPresentCallPanel(nextProps.callState)) {\n nextState.rtcPanel = nextProps.callTopic;\n }\n } else {\n // Invalid topic.\n Object.assign(nextState, {\n minSeqId: -1,\n maxSeqId: -1,\n latestClearId: -1,\n onlineSubs: [],\n title: '',\n avatar: null,\n peerMessagingDisabled: false,\n channel: false,\n pins: []\n });\n }\n } else {\n // We are still in same topic. Show the call panel if necessary.\n if (nextProps.callTopic == prevState.topic && !prevState.rtcPanel &&\n shouldPresentCallPanel(nextProps.callState)) {\n nextState.rtcPanel = nextProps.callTopic;\n }\n }\n\n if (nextProps.acs) {\n if (nextProps.acs.isWriter() != prevState.isWriter) {\n nextState.isWriter = !prevState.isWriter;\n }\n if (nextProps.acs.isReader() != prevState.isReader) {\n nextState.isReader = !prevState.isReader;\n }\n if (nextProps.acs.isAdmin() != prevState.isAdmin) {\n nextState.isAdmin = !prevState.isAdmin;\n }\n if (!nextProps.acs.isReader('given') != prevState.readingBlocked) {\n nextState.readingBlocked = !prevState.readingBlocked;\n }\n if (nextProps.acs.isSharer() != prevState.isSharer) {\n nextState.isSharer = !prevState.isSharer;\n }\n } else {\n if (prevState.isWriter) {\n nextState.isWriter = false;\n }\n if (prevState.isReader) {\n nextState.isReader = false;\n }\n if (prevState.isAdmin) {\n nextState.isAdmin = false;\n }\n if (!prevState.readingBlocked) {\n prevState.readingBlocked = true;\n }\n if (prevState.isSharer) {\n nextState.isSharer = false;\n }\n }\n\n if (isUnconfirmed(nextProps.acs) == !prevState.unconformed) {\n nextState.unconfirmed = !prevState.unconformed;\n }\n\n // Clear subscribers online when there is no connection.\n if (!nextProps.connected && prevState.onlineSubs && prevState.onlineSubs.length > 0) {\n nextState.onlineSubs = [];\n }\n\n return nextState;\n }\n\n subscribe(topic) {\n if (topic.isSubscribed() || !this.props.ready) {\n return;\n }\n\n // Is this a new topic?\n const newTopic = (this.props.newTopicParams && this.props.newTopicParams._topicName == this.props.topic);\n\n // Don't request the tags. They are useless unless the user\n // is the owner and is editing the topic.\n let getQuery = topic.startMetaQuery().withLaterDesc().withLaterSub().withAux();\n if (this.state.isReader || newTopic) {\n // Reading is either permitted or we don't know because it's a new topic. Ask for messages.\n getQuery = getQuery.withLaterData(MESSAGES_PAGE);\n if (this.state.isReader) {\n getQuery = getQuery.withLaterDel();\n }\n // And show \"loading\" spinner.\n this.setState({ fetchingMessages: true });\n }\n\n const setQuery = newTopic ? this.props.newTopicParams : undefined;\n topic.subscribe(getQuery.build(), setQuery)\n .then(ctrl => {\n if (ctrl.code == 303) {\n // Redirect to another topic requested.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', ctrl.params.topic));\n return;\n }\n if (this.state.topic != ctrl.topic) {\n this.setState({topic: ctrl.topic});\n }\n this.props.onNewTopicCreated(this.props.topic, ctrl.topic);\n // If there are unsent messages (except hard-failed and video call messages),\n // try sending them now. Hard-failed and unsent video call messages will be dropped.\n let discard = [];\n topic.queuedMessages(pub => {\n if (pub._sending) {\n return;\n }\n if (pub._fatal || (pub.head && pub.head.webrtc)) {\n // Filter out unsent failed & video call messages.\n discard.push(pub.seq);\n return;\n }\n if (topic.isSubscribed()) {\n this.retrySend(pub);\n }\n });\n if (discard.length > 0) {\n topic.delMessagesList(discard, true);\n }\n })\n .catch(err => {\n console.error(\"Failed subscription to\", this.state.topic, err);\n this.props.onError(err.message, 'err');\n const blankState = MessagesView.getDerivedStateFromProps({}, {});\n blankState.title = this.props.intl.formatMessage(messages.not_found);\n this.setState(blankState);\n });\n }\n\n leave(oldTopicName) {\n if (!oldTopicName || !this.props.tinode.isTopicCached(oldTopicName)) {\n return;\n }\n\n const oldTopic = this.props.tinode.getTopic(oldTopicName);\n if (oldTopic && oldTopic.isSubscribed()) {\n oldTopic.leave(false)\n .catch(_ => { /* do nothing here */ })\n .finally(_ => {\n // We don't care if the request succeeded or failed.\n // The topic is dead regardless.\n this.setState({fetchingMessages: false});\n oldTopic.onData = undefined;\n oldTopic.onAllMessagesReceived = undefined;\n oldTopic.onInfo = undefined;\n oldTopic.onMetaDesc = undefined;\n oldTopic.onSubsUpdated = undefined;\n oldTopic.onPres = undefined;\n oldTopic.onAuxUpdated = undefined;\n });\n }\n }\n\n // Don't use React.createRef as the ref.current is not available in componentDidMount in this component.\n handleScrollReference(node) {\n if (node) {\n node.addEventListener('scroll', this.handleScrollEvent);\n this.messagesScroller = node;\n this.messagesScroller.scrollTop = this.messagesScroller.scrollHeight -\n this.state.scrollPosition - this.messagesScroller.offsetHeight;\n }\n }\n\n // Get older messages and show/hide [go to latest message] button.\n handleScrollEvent(event) {\n const pos = event.target.scrollHeight - event.target.scrollTop - event.target.offsetHeight;\n this.setState({\n scrollPosition: pos,\n // Show [go to latest message] if far enough from bottom and scrolling down.\n showGoToLastButton: (pos > SHOW_GO_TO_LAST_DIST) && (pos < this.state.scrollPosition),\n });\n\n if (this.state.fetchingMessages) {\n return;\n }\n\n if (event.target.scrollTop <= FETCH_PAGE_TRIGGER) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n if (topic && topic.isSubscribed() && topic.msgHasMoreMessages()) {\n this.setState({fetchingMessages: true}, _ => {\n topic.getMessagesPage(MESSAGES_PAGE)\n .catch(err => this.props.onError(err.message, 'err'))\n .finally(_ => this.setState({fetchingMessages: false}));\n });\n }\n }\n }\n\n /* Mount drag and drop events */\n mountDnDEvents(dnd) {\n if (dnd) {\n dnd.addEventListener('dragstart', this.handleDragStart);\n dnd.addEventListener('dragenter', this.handleDragIn);\n dnd.addEventListener('dragleave', this.handleDragOut);\n dnd.addEventListener('dragover', this.handleDrag);\n dnd.addEventListener('drop', this.handleDrop);\n this.dndRef = dnd;\n }\n }\n\n goToLatestMessage() {\n this.setState({scrollPosition: 0});\n if (this.messagesScroller) {\n this.messagesScroller.scrollTop = this.messagesScroller.scrollHeight - this.messagesScroller.offsetHeight;\n }\n }\n\n handleDescChange(desc) {\n if (desc.public) {\n this.setState({\n title: desc.public.fn,\n avatar: makeImageUrl(desc.public.photo)\n });\n } else {\n this.setState({\n title: '',\n avatar: null\n });\n }\n\n if (desc.acs) {\n this.setState({\n isWriter: desc.acs.isWriter(),\n isReader: desc.acs.isReader(),\n isAdmin: desc.acs.isAdmin(),\n readingBlocked: !desc.acs.isReader('given'),\n unconfirmed: isUnconfirmed(desc.acs),\n });\n }\n }\n\n postReadNotification(seq) {\n // Ignore notifications if the app is invisible.\n if (!this.props.applicationVisible) {\n return;\n }\n\n // Set up the timer if it's not running already.\n if (!this.readNotificationTimer) {\n this.readNotificationTimer = setInterval(_ => {\n if (this.readNotificationQueue.length == 0) {\n // Shut down the timer if the queue is empty.\n clearInterval(this.readNotificationTimer);\n this.readNotificationTimer = null;\n return;\n }\n\n let seq = -1;\n while (this.readNotificationQueue.length > 0) {\n const n = this.readNotificationQueue[0];\n if (n.topicName != this.state.topic) {\n // Topic has changed. Drop the notification.\n this.readNotificationQueue.shift();\n continue;\n }\n\n const now = new Date();\n if (n.sendAt <= now) {\n // Remove expired notification from queue.\n this.readNotificationQueue.shift();\n seq = Math.max(seq, n.seq);\n } else {\n break;\n }\n }\n\n // Send only one notification for the whole batch of messages.\n if (seq >= 0) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n if (topic) {\n topic.noteRead(seq);\n }\n }\n }, NOTIFICATION_EXEC_INTERVAL);\n }\n\n const now = new Date();\n this.readNotificationQueue.push({\n topicName: this.state.topic,\n seq: seq,\n sendAt: now.setMilliseconds(now.getMilliseconds() + READ_DELAY)\n });\n }\n\n // Clear notification queue and timer.\n clearNotificationQueue() {\n this.readNotificationQueue = [];\n if (this.readNotificationTimer) {\n clearInterval(this.readNotificationTimer);\n this.readNotificationTimer = null;\n }\n }\n\n handleSubsUpdated() {\n if (this.state.topic) {\n const subs = [];\n const topic = this.props.tinode.getTopic(this.state.topic);\n topic.subscribers((sub) => {\n if (sub.online && sub.user != this.props.myUserId) {\n subs.push(sub);\n }\n });\n const newState = {onlineSubs: subs};\n const peer = topic.p2pPeerDesc();\n if (peer) {\n Object.assign(newState, {\n peerMessagingDisabled: isPeerRestricted(peer.acs)\n });\n } else if (this.state.peerMessagingDisabled) {\n Object.assign(newState, {\n peerMessagingDisabled: false\n });\n }\n this.setState(newState);\n }\n }\n\n // The 'msg' could be false-ish if some message ranges were deleted.\n handleMessageUpdate(msg) {\n if (!this.state.topic) {\n return;\n }\n const topic = this.props.tinode.getTopic(this.state.topic);\n if (!msg) {\n // msg could be null if one or more messages were deleted.\n // Updating state to force redraw.\n this.setState({latestClearId: topic.maxClearId()});\n return;\n }\n\n clearTimeout(this.keyPressTimer)\n this.setState({maxSeqId: topic.maxMsgSeq(), minSeqId: topic.minMsgSeq(), typingIndicator: false}, _ => {\n // Scroll to the bottom if the message is added to the end of the message\n // list if already at the bottom, otherwise show [go to latest] button.\n // Implemented as a callback to be sure the scroll height has been updated.\n if (topic.isNewMessage(msg.seq)) {\n if (this.state.scrollPosition > SHOW_GO_TO_LAST_DIST) {\n this.setState({showGoToLastButton: true});\n } else {\n this.goToLatestMessage();\n }\n } else {\n if (this.messagesScroller) {\n this.messagesScroller.scrollTop = this.messagesScroller.scrollHeight - this.state.scrollPosition -\n this.messagesScroller.offsetHeight;\n }\n }\n });\n\n // Aknowledge messages except own messages. They are\n // automatically assumed to be read and recived.\n const status = topic.msgStatus(msg, true);\n if (status >= Tinode.MESSAGE_STATUS_SENT && msg.from != this.props.myUserId) {\n this.postReadNotification(msg.seq);\n }\n }\n\n handleAllMessagesReceived(count) {\n this.setState({fetchingMessages: false});\n if (count > 0) {\n // 0 means \"latest\".\n this.postReadNotification(0);\n }\n }\n\n handleAuxUpdate(aux) {\n const pins = (aux['pins'] || []).slice();\n let selectedPin = this.state.selectedPin;\n if (pins.length > this.state.pins.length) {\n // New pins added, show the latest.\n selectedPin = 0;\n } else if (selectedPin >= pins.length) {\n selectedPin = Math.max(0, pins.length - 1);\n }\n this.setState({pins: pins, selectedPin: selectedPin});\n }\n\n handleInfoReceipt(info) {\n switch (info.what) {\n case 'kp': {\n clearTimeout(this.keyPressTimer);\n this.keyPressTimer = setTimeout(_ => this.setState({typingIndicator: false}), KEYPRESS_DELAY + 1000);\n if (!this.state.typingIndicator) {\n this.setState({typingIndicator: true});\n }\n break;\n }\n case 'read':\n case 'recv':\n // Redraw due to changed recv/read status.\n this.forceUpdate();\n break;\n default:\n console.info(\"Other change in topic: \", info.what);\n }\n }\n\n handleExpandMedia(content) {\n if (!content) {\n return;\n }\n\n if (content.video) {\n this.setState({videoPostview: content});\n } else {\n this.setState({imagePostview: content});\n }\n }\n\n handleClosePreview() {\n if (this.state.imagePreview && this.state.imagePreview.url) {\n URL.revokeObjectURL(this.state.imagePreview.url);\n }\n if (this.state.videoPreview && this.state.videoPreview.url) {\n URL.revokeObjectURL(this.state.videoPreview.url);\n }\n this.setState({ imagePostview: null, imagePreview: null, docPreview: null, videoPreview: null, videoPostview: null});\n }\n\n handleFormResponse(action, text, data) {\n if (action == 'pub') {\n this.sendMessage(Drafty.attachJSON(Drafty.parse(text), data));\n } else if (action == 'url') {\n const url = new URL(data.ref);\n const params = url.searchParams;\n for (let key in data.resp) {\n if (data.resp.hasOwnProperty(key)) {\n params.set(key, data.resp[key]);\n }\n }\n ['name', 'seq'].forEach(key => {\n if (data[key]) {\n params.set(key, data[key]);\n }\n });\n params.set('uid', this.props.myUserId);\n params.set('topic', this.state.topic);\n url.search = params;\n window.open(url, '_blank');\n } else {\n console.info(\"Unknown action in form\", action);\n }\n }\n\n handleContextClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.showContextMenu({ topicName: this.state.topic, y: e.pageY, x: e.pageX });\n }\n\n handleShowMessageContextMenu(params, messageSpecificMenuItems) {\n if (params.userFrom == 'chan') {\n params.userFrom = this.state.topic;\n params.userName = this.state.title;\n }\n params.topicName = this.state.topic;\n const menuItems = messageSpecificMenuItems || [];\n const topic = this.props.tinode.getTopic(params.topicName);\n if (topic) {\n if (!topic.isChannelType()) {\n menuItems.push('message_delete');\n }\n const acs = topic.getAccessMode();\n if (acs && acs.isDeleter()) {\n menuItems.push('message_delete_hard');\n }\n }\n this.props.showContextMenu(params, menuItems);\n }\n\n handleNewChatAcceptance(action) {\n this.props.onNewChat(this.state.topic, action);\n }\n\n handleEnablePeer(e) {\n e.preventDefault();\n this.props.onChangePermissions(this.state.topic, DEFAULT_P2P_ACCESS_MODE, this.state.topic);\n }\n\n sendKeyPress(audio) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n if (topic.isSubscribed()) {\n if (audio) {\n topic.noteRecording(true);\n } else {\n topic.noteKeyPress();\n }\n }\n }\n\n // sendMessage sends the message with an optional subscription to topic first.\n sendMessage(msg, uploadCompletionPromise, uploader) {\n let head;\n if (this.props.forwardMessage) {\n // We are forwarding a message.\n msg = this.props.forwardMessage.msg;\n head = this.props.forwardMessage.head;\n this.handleCancelReply();\n } else if (this.state.reply) {\n if (this.state.reply.editing) {\n if (msg == this.state.contentToEdit) {\n // Message unchanged.\n this.handleCancelReply();\n return;\n }\n // Editing an existing message.\n head = {replace: ':' + this.state.reply.seq};\n } else if (this.state.reply.content) {\n // Replying to a message in this topic.\n // Turn it into Drafty so we can make a quoted Drafty object later.\n head = {reply: '' + this.state.reply.seq};\n if (typeof msg == 'string') {\n msg = Drafty.parse(msg);\n }\n msg = Drafty.append(Drafty.sanitizeEntities(this.state.reply.content), msg);\n }\n this.handleCancelReply();\n }\n this.props.sendMessage(msg, uploadCompletionPromise, uploader, head);\n }\n\n // Retry sending a message.\n retrySend(pub) {\n this.props.sendMessage(pub.content, undefined, undefined, pub.head)\n .then(_ => {\n // All good. Remove the original message draft from the cache.\n const topic = this.props.tinode.getTopic(this.state.topic);\n topic.delMessagesList([pub.seq], true);\n });\n }\n\n // Send attachment as Drafty message:\n // - if file is too large, upload it and send a s link.\n // - if file is small enough, just send it in-band.\n sendFileAttachment(file) {\n // Server-provided limit reduced for base64 encoding and overhead.\n const maxInbandAttachmentSize = (this.props.tinode.getServerParam('maxMessageSize',\n MAX_INBAND_ATTACHMENT_SIZE) * 0.75 - 1024) | 0;\n\n if (file.size > maxInbandAttachmentSize) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n if (!uploader) {\n this.props.onError(this.props.intl.formatMessage(messages.cannot_initiate_upload));\n return;\n }\n const uploadCompletionPromise = uploader.upload(file);\n const msg = Drafty.attachFile(null, {\n mime: file.type,\n filename: file.name,\n size: file.size,\n urlPromise: uploadCompletionPromise\n });\n // Pass data and the uploader to the TinodeWeb.\n this.sendMessage(msg, uploadCompletionPromise, uploader);\n } else {\n // Small enough to send inband.\n fileToBase64(file)\n .then(b64 => this.sendMessage(Drafty.attachFile(null, {\n mime: b64.mime,\n data: b64.bits,\n filename: b64.name,\n size: file.size\n })))\n .catch(err => this.props.onError(err.message, 'err'));\n }\n }\n\n // handleAttachFile method is called when [Attach file] button is clicked: launch attachment preview.\n handleAttachFile(file) {\n const maxExternAttachmentSize = this.props.tinode.getServerParam('maxFileUploadSize', MAX_EXTERN_ATTACHMENT_SIZE);\n\n if (file.size > maxExternAttachmentSize) {\n // Too large.\n this.props.onError(this.props.intl.formatMessage(messages.file_attachment_too_large,\n {size: bytesToHumanSize(file.size), limit: bytesToHumanSize(maxExternAttachmentSize)}), 'err');\n } else {\n this.setState({\n docPreview: {\n file: file,\n name: file.name,\n size: file.size,\n type: file.type\n }\n });\n }\n }\n\n handleCallHangup(topic, seq) {\n this.props.onVideoCallClosed();\n this.setState({\n rtcPanel: null\n });\n this.props.onCallHangup(topic, seq);\n }\n\n // sendImageAttachment sends the image bits as Drafty message.\n sendImageAttachment(caption, blob) {\n const mime = this.state.imagePreview.mime;\n const width = this.state.imagePreview.width;\n const height = this.state.imagePreview.height;\n const fname = this.state.imagePreview.filename;\n\n // Server-provided limit reduced for base64 encoding and overhead.\n const maxInbandAttachmentSize = (this.props.tinode.getServerParam('maxMessageSize',\n MAX_INBAND_ATTACHMENT_SIZE) * 0.75 - 1024) | 0;\n\n if (blob.size > maxInbandAttachmentSize) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n if (!uploader) {\n this.props.onError(this.props.intl.formatMessage(messages.cannot_initiate_upload));\n return;\n }\n const uploadCompletionPromise = uploader.upload(blob);\n\n // Make small preview to show while uploading.\n imageScaled(blob, IMAGE_PREVIEW_DIM, IMAGE_PREVIEW_DIM, -1, false)\n // Convert tiny image into base64 for serialization and previewing.\n .then(scaled => blobToBase64(scaled.blob))\n .then(b64 => {\n let msg = Drafty.insertImage(null, 0, {\n mime: mime,\n _tempPreview: b64.bits, // This preview will not be serialized.\n bits: b64.bits, // Image thumbnail.\n width: width,\n height: height,\n filename: fname,\n size: blob.size,\n urlPromise: uploadCompletionPromise\n });\n if (caption) {\n msg = Drafty.appendLineBreak(msg);\n msg = Drafty.append(msg, Drafty.parse(caption));\n }\n // Pass data and the uploader to the TinodeWeb.\n this.sendMessage(msg, uploadCompletionPromise, uploader);\n })\n .catch(err => this.props.onError(err, 'err'));\n return;\n }\n\n // Send the image inband if it's not too big. The image has been scaled already\n // in image preview.\n blobToBase64(blob)\n .then(b64 => {\n let msg = Drafty.insertImage(null, 0, {\n mime: b64.mime,\n bits: b64.bits,\n width: width,\n height: height,\n filename: fname,\n size: blob.size\n });\n if (caption) {\n msg = Drafty.appendLineBreak(msg);\n msg = Drafty.append(msg, Drafty.parse(caption));\n }\n this.sendMessage(msg);\n });\n }\n\n // sendVideoAttachment sends the video bits as Drafty message.\n sendVideoAttachment(caption, videoBlob, previewBlob, params) {\n const width = params.width;\n const height = params.height;\n\n // Server-provided limit reduced for base64 encoding and overhead.\n const maxInbandAttachmentSize = (this.props.tinode.getServerParam('maxMessageSize',\n MAX_INBAND_ATTACHMENT_SIZE) * 0.75 - 1024) | 0;\n\n const uploads = [];\n let uploader;\n if ((videoBlob.size + previewBlob.size) > maxInbandAttachmentSize) {\n // One or both are too large to send inband. Uploading out of band and sending as a link.\n uploader = this.props.tinode.getLargeFileHelper();\n if (!uploader) {\n this.props.onError(this.props.intl.formatMessage(messages.cannot_initiate_upload));\n return;\n }\n\n uploads[0] = videoBlob.size > maxInbandAttachmentSize * 0.675 ? uploader.upload(videoBlob) : null;\n uploads[1] = previewBlob.size > maxInbandAttachmentSize * 0.275 ? uploader.upload(previewBlob) : null;\n }\n\n if (uploads.length == 0) {\n // Both video and preview are small enough to send inband.\n Promise.all([blobToBase64(videoBlob), blobToBase64(previewBlob)])\n .then(b64s => {\n const [v64, i64] = b64s;\n let msg = Drafty.insertVideo(null, 0, {\n mime: v64.mime,\n bits: v64.bits,\n preview: i64.bits,\n premime: i64.mime,\n width: width,\n height: height,\n duration: params.duration,\n filename: params.name,\n size: videoBlob.size\n });\n if (caption) {\n msg = Drafty.appendLineBreak(msg);\n msg = Drafty.append(msg, Drafty.parse(caption));\n }\n this.sendMessage(msg);\n });\n return;\n }\n\n const uploadCompletionPromise = Promise.all(uploads);\n\n const b64conv = [];\n // Small video converted to base64.\n b64conv[0] = uploads[0] ? null : blobToBase64(videoBlob);\n // Full-size preview fits inline.\n b64conv[1] = uploads[1] ? null : imageScaled(previewBlob, MAX_IMAGE_DIM, MAX_IMAGE_DIM, -1, false)\n .then(scaled => blobToBase64(scaled.blob));\n // Small preview to show while uploading.\n b64conv[2] = imageScaled(previewBlob, VIDEO_PREVIEW_DIM, VIDEO_PREVIEW_DIM, -1, false)\n .then(scaled => blobToBase64(scaled.blob));\n // Convert tiny image into base64 for serialization and previewing.\n Promise.all(b64conv)\n .then(b64s => {\n const [video, img, preview] = b64s;\n let msg = Drafty.insertVideo(null, 0, {\n mime: params.mime,\n bits: video ? video.bits : null,\n _tempPreview: preview.bits,\n preview: img ? img.bits : preview.bits,\n premime: img ? img.mime : preview.mime,\n width: width,\n height: height,\n duration: params.duration,\n filename: params.name,\n size: videoBlob.size,\n urlPromise: uploadCompletionPromise\n });\n\n if (caption) {\n msg = Drafty.appendLineBreak(msg);\n msg = Drafty.append(msg, Drafty.parse(caption));\n }\n // Pass data and the uploader to the TinodeWeb.\n this.sendMessage(msg, uploadCompletionPromise, uploader);\n })\n .catch(err => this.props.onError(err.message, 'err'));\n }\n\n // handleAttachImageOrVideo method is called when [Attach image or video] button is clicked: launch image or video preview.\n handleAttachImageOrVideo(file) {\n const maxExternAttachmentSize = this.props.tinode.getServerParam('maxFileUploadSize', MAX_EXTERN_ATTACHMENT_SIZE);\n\n if (file.type.startsWith('video/')) {\n this.setState({videoPreview: {\n url: URL.createObjectURL(file),\n blob: file,\n filename: file.name,\n size: file.size,\n mime: file.type\n }});\n return;\n }\n\n // Get image dimensions and size, optionally scale it down.\n imageScaled(file, MAX_IMAGE_DIM, MAX_IMAGE_DIM, maxExternAttachmentSize, false)\n .then(scaled => {\n this.setState({imagePreview: {\n url: URL.createObjectURL(scaled.blob),\n blob: scaled.blob,\n filename: scaled.name,\n width: scaled.width,\n height: scaled.height,\n size: scaled.blob.size,\n mime: scaled.mime\n }});\n }).catch(err => {\n this.props.onError(err.message, 'err');\n });\n }\n\n // handleFileDrop is called when the user drags & drops a file upon the message view.\n handleFileDrop(files) {\n if (!files || files.length == 0) {\n return;\n }\n const file = files[0];\n if (file.type && file.type.startsWith('image/')) {\n this.handleAttachImageOrVideo(file);\n } else {\n this.handleAttachFile(file);\n }\n }\n\n // sendAudioAttachment sends audio bits inband as Drafty message (no preview).\n sendAudioAttachment(url, preview, duration) {\n fetch(url)\n .then(result => result.blob())\n .then(blob => {\n // Server-provided limit reduced for base64 encoding and overhead.\n const maxInbandAttachmentSize = this.props.tinode.getServerParam('maxMessageSize', MAX_INBAND_ATTACHMENT_SIZE) * 0.75 - 1024;\n if (blob.size > maxInbandAttachmentSize) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n if (!uploader) {\n this.props.onError(this.props.intl.formatMessage(messages.cannot_initiate_upload));\n return;\n }\n const uploadCompletionPromise = uploader.upload(blob);\n const msg = Drafty.appendAudio(null, {\n mime: blob.type,\n size: blob.size,\n duration: duration,\n preview: preview,\n urlPromise: uploadCompletionPromise\n });\n // Pass data and the uploader to the TinodeWeb.\n this.sendMessage(msg, uploadCompletionPromise, uploader);\n } else {\n // Small enough to send inband.\n blobToBase64(blob)\n .then(b64 => {\n this.sendMessage(Drafty.appendAudio(null, {\n mime: b64.mime,\n bits: b64.bits,\n size: blob.size,\n duration: duration,\n preview: preview,\n }))\n })\n }\n })\n .catch(err => {this.props.onError(err.message, 'err')});;\n }\n\n handleCancelUpload(seq, uploader) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n const found = topic.findMessage(seq);\n if (found) {\n found._cancelled = true;\n }\n uploader.cancel();\n }\n\n // seq: seq ID of the source message\n // context: message content.\n // senderId: UID of the sender of the source message.\n // senderName: full name of the sender of the original message.\n handlePickReply(seq, content, senderId, senderName) {\n if (!seq || !content) {\n this.setState({reply: null});\n return;\n }\n\n content = typeof content == 'string' ? Drafty.init(content) : content;\n if (Drafty.isValid(content)) {\n content = Drafty.replyContent(content, QUOTED_REPLY_LENGTH);\n } else {\n // /!\\ invalid content.\n content = Drafty.append(Drafty.init('\\u26A0 '),\n Drafty.wrapInto(this.props.intl.formatMessage(messages.invalid_content), 'EM'));\n }\n\n this.setState({\n reply: {\n content: Drafty.quote(senderName, senderId, content),\n seq: seq\n }\n });\n this.props.onCancelForwardMessage();\n }\n\n // seq: seq ID of the message to edit.\n // context: message content.\n handleEditMessage(seq, content) {\n if (!seq || !content) {\n this.setState({reply: null});\n return;\n }\n\n content = typeof content == 'string' ? Drafty.init(content) : content;\n const editable = Drafty.toMarkdown(content);\n if (Drafty.isValid(content)) {\n content = Drafty.replyContent(content, EDIT_PREVIEW_LENGTH);\n } else {\n // /!\\ invalid content.\n content = Drafty.append(Drafty.init('\\u26A0 '),\n Drafty.wrapInto(this.props.intl.formatMessage(messages.invalid_content), 'EM'));\n }\n\n this.setState({\n reply: {\n content: Drafty.quote(this.props.intl.formatMessage(messages.editing_message), null, content),\n seq: seq,\n editing: true\n },\n contentToEdit: editable\n });\n this.props.onCancelForwardMessage();\n }\n\n\n handleCancelReply() {\n this.setState({reply: null, contentToEdit: null});\n this.props.onCancelForwardMessage();\n }\n\n handleQuoteClick(replyToSeq) {\n const ref = this.getOrCreateMessageRef(replyToSeq);\n if (ref && ref.current) {\n ref.current.scrollIntoView({block: \"center\", behavior: \"smooth\"});\n ref.current.classList.add('flash');\n setTimeout(_ => {ref.current.classList.remove('flash')} , 1000);\n } else {\n console.error(\"Unresolved message ref\", replyToSeq);\n }\n }\n\n handleUnpinMessage(seq) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n topic.pinMessage(seq, false);\n }\n\n isDragEnabled() {\n return this.state.isWriter && !this.state.unconfirmed && !this.props.forwardMessage && !this.state.peerMessagingDisabled;\n }\n\n handleDragStart(e) {\n e.preventDefault();\n e.stopPropagation();\n e.dataTransfer.clearData();\n }\n\n handleDragIn(e) {\n e.preventDefault();\n e.stopPropagation();\n this.dragCounter++;\n if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {\n this.setState({dragging: true});\n }\n }\n\n handleDragOut(e) {\n e.preventDefault();\n e.stopPropagation();\n this.dragCounter--;\n if (this.dragCounter <= 0) {\n this.setState({dragging: false});\n }\n }\n\n handleDrag(e) {\n e.preventDefault();\n e.stopPropagation();\n }\n\n handleDrop(e) {\n e.preventDefault();\n e.stopPropagation();\n this.setState({dragging: false});\n if (this.isDragEnabled() && e.dataTransfer.files && e.dataTransfer.files.length > 0) {\n this.handleFileDrop(e.dataTransfer.files);\n this.dragCounter = 0;\n }\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n\n let component;\n if (!this.state.topic) {\n component = (\n \n );\n } else {\n let component2;\n if (this.state.imagePreview) {\n // Preview image before sending.\n component2 = (\n \n );\n } else if (this.state.videoPreview) {\n // Preview video.\n component2 = (\n \n );\n } else if (this.state.imagePostview) {\n // Expand received image.\n component2 = (\n \n );\n } else if (this.state.videoPostview) {\n // Play received video.\n component2 = (\n \n );\n } else if (this.state.docPreview) {\n // Preview attachment before sending.\n component2 = (\n \n );\n } else if (this.state.rtcPanel) {\n component2 = (\n \n );\n } else {\n const topic = this.props.tinode.getTopic(this.state.topic);\n const isChannel = topic.isChannelType();\n const groupTopic = topic.isGroupType() && !isChannel;\n const icon_badges = [];\n if (topic.trusted) {\n if (topic.trusted.verified) {\n icon_badges.push({icon: 'verified', color: 'badge-inv'});\n }\n if (topic.trusted.staff) {\n icon_badges.push({icon: 'staff', color: 'badge-inv'});\n }\n if (topic.trusted.danger) {\n icon_badges.push({icon: 'dangerous', color: 'badge-inv'});\n }\n }\n\n const pinnedMessages = [];\n this.state.pins.forEach(seq => pinnedMessages.push(topic.findMessage(seq)));\n\n const messageNodes = [];\n let previousFrom = null;\n let prevDate = null;\n let chatBoxClass = null;\n topic.messages((msg, prev, next, i) => {\n let nextFrom = next ? (next.from || 'chan') : null;\n\n let sequence = 'single';\n let thisFrom = msg.from || 'chan';\n if (thisFrom == previousFrom) {\n if (thisFrom == nextFrom) {\n sequence = 'middle';\n } else {\n sequence = 'last';\n }\n } else if (thisFrom == nextFrom) {\n sequence = 'first';\n }\n previousFrom = thisFrom;\n\n const isReply = !(thisFrom == this.props.myUserId);\n const deliveryStatus = topic.msgStatus(msg, true);\n\n let userFrom = thisFrom, userName, userAvatar;\n const user = topic.userDesc(thisFrom);\n if (user && user.public) {\n userName = user.public.fn;\n userAvatar = makeImageUrl(user.public.photo);\n }\n chatBoxClass = groupTopic ? 'chat-box group' : 'chat-box';\n\n // Ref for this chat message.\n const ref = this.getOrCreateMessageRef(msg.seq);\n let replyToSeq = msg.head ? parseInt(msg.head.reply) : null;\n if (!replyToSeq || isNaN(replyToSeq)) {\n replyToSeq = null;\n }\n\n if (msg.hi) {\n // Deleted message.\n messageNodes.push(\n \n );\n } else {\n const thisDate = new Date(msg.ts);\n // This message was sent on a different date than the previous.\n if (!prevDate || prevDate.toDateString() != thisDate.toDateString()) {\n messageNodes.push(\n \n );\n prevDate = thisDate;\n }\n messageNodes.push(\n \n );\n }\n });\n\n let lastSeen = null;\n if (isChannel) {\n lastSeen = formatMessage(messages.channel);\n } else {\n const cont = this.props.tinode.getMeTopic().getContact(this.state.topic);\n if (cont && Tinode.isP2PTopicName(cont.topic)) {\n if (cont.online) {\n lastSeen = formatMessage(messages.online_now);\n } else if (cont.seen) {\n lastSeen = formatMessage(messages.last_seen) + \": \" +\n shortDateFormat(cont.seen.when, this.props.intl.locale);\n // TODO: also handle user agent in c.seen.ua\n }\n }\n }\n const avatar = this.state.avatar || true;\n const online = this.state.deleted ? null :\n this.props.online ? 'online' + (this.state.typingIndicator ? ' typing' : '') : 'offline';\n\n const titleClass = 'panel-title' + (this.state.deleted ? ' deleted' : '');\n\n let messagesComponent = (\n <>\n
\n \n
\n
    \n {messageNodes}\n
\n
\n {!this.state.isReader ?\n
\n {this.state.readingBlocked ?\n
\n \n
\n : null }\n
\n : null }\n
\n {this.state.peerMessagingDisabled && !this.state.unconfirmed ?\n
\n block .\n
: null}\n {this.state.unconfirmed ?\n \n :\n }\n \n );\n\n component2 = (\n <>\n
\n {this.props.displayMobile ?\n {e.preventDefault(); this.props.onHideMessagesView();}}>\n arrow_back\n \n :\n null}\n
\n \n {!isChannel ? : null}\n
\n
\n
{\n this.state.title ||\n \n }
\n
{lastSeen}
\n
\n {!this.props.displayMobile ?\n this.setState({selectedPin: index})}\n onSelected={this.handleQuoteClick}\n onCancel={this.handleUnpinMessage} />\n : null}\n {groupTopic ?\n :\n null\n }\n \n
\n {this.props.displayMobile ?\n <>\n this.setState({selectedPin: index})}\n onSelected={this.handleQuoteClick}\n onCancel={this.handleUnpinMessage} />\n \n \n : null}\n \n {messagesComponent}\n {this.state.dragging && this.isDragEnabled() ?\n
{formatMessage(messages.drag_file)}
\n : null}\n \n );\n }\n component =
{component2}
\n }\n return component;\n }\n};\n\nexport default injectIntl(MessagesView);\n","// Create new topic and invite users or send an invite.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport ContactList from '../widgets/contact-list.jsx';\nimport NewTopicById from '../widgets/new-topic-by-id.jsx';\nimport NewTopicGroup from '../widgets/new-topic-group.jsx';\nimport SearchContacts from '../widgets/search-contacts.jsx';\n\nimport HashNavigation from '../lib/navigation.js';\nimport { theCard } from '../lib/utils.js';\n\nconst messages = defineMessages({\n search_for_contacts: {\n id: \"search_for_contacts\",\n defaultMessage: \"Use search to find contacts\",\n description: \"Text shown in contacts view when user entered no search query.\"\n },\n search_no_results: {\n id: \"search_no_results\",\n defaultMessage: \"Search returned no results\",\n description: \"Text shown in contacts view when query returned no results.\"\n },\n search_placeholder: {\n id: \"search_placeholder\",\n defaultMessage: \"List like email:alice@example.com, tel:17025550003...\",\n description: \"Placeholder in contacts search field\"\n },\n});\n\nclass NewTopicView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n tabSelected: 'find',\n searchQuery: null\n };\n\n this.handleTabClick = this.handleTabClick.bind(this);\n this.handleSearchContacts = this.handleSearchContacts.bind(this);\n this.handleSearchResultSelected = this.handleSearchResultSelected.bind(this);\n this.handleNewGroupSubmit = this.handleNewGroupSubmit.bind(this);\n this.handleGroupByID = this.handleGroupByID.bind(this);\n }\n\n componentDidMount() {\n this.props.onInitFind();\n }\n\n handleTabClick(e) {\n e.preventDefault();\n HashNavigation.navigateTo(HashNavigation.addUrlParam(window.location.hash, 'tab', e.currentTarget.dataset.id));\n this.setState({tabSelected: e.currentTarget.dataset.id});\n }\n\n handleSearchContacts(query) {\n this.props.onSearchContacts(query);\n this.setState({searchQuery: Tinode.isNullValue(query) ? null : query});\n }\n\n handleSearchResultSelected(name) {\n if (this.state.tabSelected == 'find') {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'tab'));\n this.props.onCreateTopic(name);\n }\n }\n\n handleNewGroupSubmit(name, description, dataUrl, priv, tags, isChannel) {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'tab'));\n this.props.onCreateTopic(undefined,\n {public: theCard(name, dataUrl, null, description), private: priv, tags: tags}, isChannel);\n }\n\n handleGroupByID(topicName) {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'tab'));\n this.props.onCreateTopic(topicName);\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n const no_contacts_placeholder = formatMessage(this.state.searchQuery ?\n messages.search_no_results : messages.search_for_contacts);\n const search_placeholder = formatMessage(messages.search_placeholder);\n return (\n
\n \n {this.state.tabSelected === 'grp' ?\n :\n this.state.tabSelected === 'byid' ?\n :\n
\n \n \n
}\n
\n );\n }\n};\n\nexport default injectIntl(NewTopicView);\n","// Tinode config panel.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport CheckBox from '../widgets/checkbox.jsx';\n\nimport HostSelector from '../widgets/host-selector.jsx';\n\nexport default class SettingsView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n transport: props.transport || 'def',\n serverAddress: props.serverAddress,\n secureConnection: props.secureConnection,\n };\n\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleTransportSelected = this.handleTransportSelected.bind(this);\n this.handleServerAddressChange = this.handleServerAddressChange.bind(this);\n this.handleToggleSecure = this.handleToggleSecure.bind(this);\n }\n\n handleSubmit(e) {\n e.preventDefault();\n this.props.onUpdate({\n transport: this.state.transport,\n serverAddress: this.state.serverAddress,\n secureConnection: this.state.secureConnection,\n });\n }\n\n handleTransportSelected(e) {\n this.setState({transport: e.currentTarget.value});\n }\n\n handleServerAddressChange(name) {\n this.setState({serverAddress: name});\n }\n\n handleToggleSecure(e) {\n this.setState({secureConnection: !this.state.secureConnection});\n }\n\n render() {\n const names = {def: \"default\", ws: \"websocket\", lp: \"long polling\"};\n const transportOptions = [];\n ['def', 'ws', 'lp'].forEach(item => {\n const id = 'transport-' + item;\n const name = names[item];\n transportOptions.push(\n
  • \n \n \n
  • \n );\n });\n\n return (\n
    \n
    \n \n
    \n \n
    \n \n
    \n
    \n \n
    \n
    \n
      \n {transportOptions}\n
    \n
    \n
    \n \n
    \n \n );\n }\n};\n","import React, { Suspense } from 'react';\nimport { defineMessages, FormattedMessage, injectIntl } from 'react-intl';\n\nimport ErrorPanel from '../widgets/error-panel.jsx';\nimport LoadSpinner from '../widgets/load-spinner.jsx';\nimport SideNavbar from '../widgets/side-navbar.jsx';\nimport TopicCommonView from './topic-common-view.jsx';\n\nconst AccountSettingsView = React.lazy(_ => import('./account-settings-view.jsx'));\nimport ContactsView from './contacts-view.jsx';\nconst CreateAccountView = React.lazy(_ => import('./create-account-view.jsx'));\nimport AccNotificationsView from './acc-notifications-view.jsx';\nimport AccSecurityView from './acc-security-view.jsx';\nimport AccSupportView from './acc-support-view.jsx';\nimport LoginView from './login-view.jsx';\nimport NewTopicView from './new-topic-view.jsx';\nconst PasswordResetView = React.lazy(_ => import('./password-reset-view.jsx'));\nimport SettingsView from './settings-view.jsx';\nimport ValidationView from './validation-view.jsx';\n\n// Panel titles for translation.\nconst messages = defineMessages({\n login: {\n id: 'sidepanel_title_login',\n description: 'Sidepanel title for LoginView.',\n defaultMessage: 'Sign In'\n },\n register: {\n id: 'sidepanel_title_register',\n description: 'Sidepanel title for CreateAccountView.',\n defaultMessage: 'Create Account'\n },\n settings: {\n id: 'sidepanel_title_settings',\n description: 'Sidepanel title for SettingsView.',\n defaultMessage: 'Settings'\n },\n edit: {\n id: 'sidepanel_title_account_settings',\n description: 'Sidepanel title for AccountSettingsView.',\n defaultMessage: 'Account Settings'\n },\n general: {\n id: 'panel_title_general',\n description: 'Title for TopicCommon.',\n defaultMessage: 'General'\n },\n security: {\n id: 'panel_title_security',\n description: 'Title for TopicSecirity and AccSecurity.',\n defaultMessage: 'Security'\n },\n crop: {\n id: 'panel_title_crop',\n description: 'Title for AvatarCropView.',\n defaultMessage: 'Drag to Adjust'\n },\n notif: {\n id: 'sidepanel_title_acc_notifications',\n description: 'Sidepanel title for AccNotificationsView.',\n defaultMessage: 'Notifications'\n },\n support: {\n id: 'sidepanel_title_acc_support',\n description: 'Sidepanel title for AccSupportView.',\n defaultMessage: 'Support'\n },\n newtpk: {\n id: 'sidepanel_title_newtpk',\n description: 'Sidepanel title for NewTopicView.',\n defaultMessage: 'Start New Chat'\n },\n cred: {\n id: 'sidepanel_title_cred',\n description: 'Sidepanel title for ValidationView.',\n defaultMessage: 'Confirm Credentials'\n },\n reset: {\n id: 'sidepanel_title_reset',\n description: 'Sidepanel title for PasswordResetView.',\n defaultMessage: 'Reset Password'\n },\n archive: {\n id: 'sidepanel_title_archive',\n description: 'Sidepanel title for ContactsView-Archive.',\n defaultMessage: 'Archived Chats'\n },\n blocked: {\n id: 'sidepanel_title_blocked',\n description: 'Sidepanel title for ContactsView-Blocked.',\n defaultMessage: 'Blocked Chats'\n }\n});\n\nclass SidepanelView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleNewTopic = this.handleNewTopic.bind(this);\n }\n\n handleNewTopic() {\n this.props.onNavigate('newtpk');\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n const view = this.props.state || (this.props.myUserId ? 'contacts' : 'login');\n\n let title, avatar, badges;\n if (view == 'contacts') {\n title = this.props.title;\n avatar = this.props.avatar ? this.props.avatar : true;\n badges = this.props.trustedBadges;\n } else {\n title = formatMessage(messages[view]);\n avatar = false;\n badges = null;\n }\n\n let onCancel;\n if (['login', 'contacts'].indexOf(view) == -1) {\n onCancel = this.props.onCancel;\n }\n\n return (\n
    \n \n\n \n\n \n\n {view === 'login' ?\n :\n\n view === 'register' ?\n
    }>\n \n :\n\n view === 'settings' ?\n :\n\n view === 'edit' ?\n
    }>\n \n :\n\n (view === 'general' || view === 'crop') ?\n :\n\n view === 'notif' ?\n :\n\n view === 'security' ?\n :\n\n view === 'support' ?\n :\n\n (view === 'contacts' || view == 'archive' || view == 'blocked') ?\n :\n\n view === 'newtpk' ?\n :\n\n view === 'cred' ?\n :\n\n view === 'reset' ?\n
    }>\n \n :\n null}\n
    \n );\n }\n};\n\nexport default injectIntl(SidepanelView);\n","// The top-level class to hold all functionality together.\nimport React, { Suspense } from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport { initializeApp as firebaseInitApp } from 'firebase/app';\nimport { getMessaging as firebaseGetMessaging, getToken as firebaseGetToken,\n deleteToken as firebaseDelToken, onMessage as firebaseOnMessage } from 'firebase/messaging';\n\nimport { Drafty, Tinode } from 'tinode-sdk';\n\nimport Alert from '../widgets/alert.jsx';\nimport ContextMenu from '../widgets/context-menu.jsx';\nimport ForwardDialog from '../widgets/forward-dialog.jsx';\nimport CallIncoming from '../widgets/call-incoming.jsx';\nconst PhoneCountrySelector = React.lazy(_ => import('../widgets/phone-country-selector.jsx'));\n\nimport InfoView from './info-view.jsx';\nimport MessagesView from './messages-view.jsx';\nimport SidepanelView from './sidepanel-view.jsx';\n\nimport { API_KEY, APP_NAME, DEFAULT_P2P_ACCESS_MODE, FORWARDED_PREVIEW_LENGTH, LOGGING_ENABLED,\n MEDIA_BREAKPOINT } from '../config.js';\nimport { CALL_STATE_NONE, CALL_STATE_OUTGOING_INITATED,\n CALL_STATE_INCOMING_RECEIVED, CALL_STATE_IN_PROGRESS,\n CALL_HEAD_STARTED } from '../constants.js';\nimport { PACKAGE_VERSION } from '../version.js';\nimport { base64ReEncode, makeImageUrl } from '../lib/blob-helpers.js';\nimport { detectServerAddress, isLocalHost, isSecureConnection } from '../lib/host-name.js';\nimport LocalStorageUtil from '../lib/local-storage.js';\nimport HashNavigation from '../lib/navigation.js';\nimport { secondsToTime } from '../lib/strformat.js'\nimport { updateFavicon } from '../lib/utils.js';\n\n// Sound to play on message received.\nconst POP_SOUND = new Audio('audio/msg.m4a');\n\nconst messages = defineMessages({\n reconnect_countdown: {\n id: 'reconnect_countdown',\n defaultMessage: 'Disconnected. Reconnecting in {seconds}…',\n description: 'Message shown when an app update is available.'\n },\n reconnect_now: {\n id: 'reconnect_now',\n defaultMessage: 'Try now',\n description: 'Prompt for reconnecting now'\n },\n push_init_failed: {\n id: 'push_init_failed',\n defaultMessage: 'Failed to initialize push notifications',\n description: 'Error message when push notifications have failed to initialize.'\n },\n invalid_security_token: {\n id: 'invalid_security_token',\n defaultMessage: 'Invalid security token',\n description: 'Error message when resetting password.'\n },\n no_connection: {\n id: 'no_connection',\n defaultMessage: 'No connection',\n description: 'Warning that the user is offline.'\n },\n code_doesnot_match: {\n id: 'code_doesnot_match',\n defaultMessage: 'Code does not match',\n description: 'Error message when the credential validation code is incorrect.'\n },\n menu_item_info: {\n id: 'menu_item_info',\n defaultMessage: 'Info',\n description: 'Show extended topic information'\n },\n menu_item_audio_call: {\n id: 'menu_item_audio_call',\n defaultMessage: 'Call',\n description: 'Start audio call'\n },\n menu_item_video_call: {\n id: 'menu_item_video_call',\n defaultMessage: 'Video call',\n description: 'Start video call'\n },\n cred_confirmed_successfully: {\n id: 'cred_confirmed_successfully',\n defaultMessage: 'Confirmed successfully',\n description: 'Message explaining that the credential was successfully validated.'\n }\n});\n\nclass TinodeWeb extends React.Component {\n constructor(props) {\n super(props);\n\n this.selfRef = React.createRef();\n\n this.state = this.getBlankState();\n\n this.handleResize = this.handleResize.bind(this);\n this.handleHashRoute = this.handleHashRoute.bind(this);\n this.handleOnline = this.handleOnline.bind(this);\n this.checkForAppUpdate = this.checkForAppUpdate.bind(this);\n this.handleVisibilityEvent = this.handleVisibilityEvent.bind(this);\n this.handleError = this.handleError.bind(this);\n this.handleLoginRequest = this.handleLoginRequest.bind(this);\n this.handlePersistenceChange = this.handlePersistenceChange.bind(this);\n this.handleConnected = this.handleConnected.bind(this);\n this.handleAutoreconnectIteration = this.handleAutoreconnectIteration.bind(this);\n this.doLogin = this.doLogin.bind(this);\n this.handleLoginSuccessful = this.handleLoginSuccessful.bind(this);\n this.handleDisconnect = this.handleDisconnect.bind(this);\n this.tnMeMetaDesc = this.tnMeMetaDesc.bind(this);\n this.tnMeContactUpdate = this.tnMeContactUpdate.bind(this);\n this.tnMeSubsUpdated = this.tnMeSubsUpdated.bind(this);\n this.resetContactList = this.resetContactList.bind(this);\n this.tnInitFind = this.tnInitFind.bind(this);\n this.tnFndSubsUpdated = this.tnFndSubsUpdated.bind(this);\n this.handleSearchContacts = this.handleSearchContacts.bind(this);\n this.handleTopicSelected = this.handleTopicSelected.bind(this);\n this.handleHideMessagesView = this.handleHideMessagesView.bind(this);\n this.handleSendMessage = this.handleSendMessage.bind(this);\n this.handleNewChatInvitation = this.handleNewChatInvitation.bind(this);\n this.handleNewAccount = this.handleNewAccount.bind(this);\n this.handleNewAccountRequest = this.handleNewAccountRequest.bind(this);\n this.handleUpdatePasswordRequest = this.handleUpdatePasswordRequest.bind(this);\n this.handleUpdateAccountTagsRequest = this.handleUpdateAccountTagsRequest.bind(this);\n this.handleToggleIncognitoMode = this.handleToggleIncognitoMode.bind(this);\n this.handleSettings = this.handleSettings.bind(this);\n this.handleGlobalSettings = this.handleGlobalSettings.bind(this);\n this.handleShowArchive = this.handleShowArchive.bind(this);\n this.handleShowBlocked = this.handleShowBlocked.bind(this);\n this.handleToggleMessageSounds = this.handleToggleMessageSounds.bind(this);\n this.handleCredAdd = this.handleCredAdd.bind(this);\n this.handleCredDelete = this.handleCredDelete.bind(this);\n this.handleCredConfirm = this.handleCredConfirm.bind(this);\n this.initFCMessaging = this.initFCMessaging.bind(this);\n this.toggleFCMToken = this.toggleFCMToken.bind(this);\n this.handlePushMessage = this.handlePushMessage.bind(this);\n this.handleSidepanelCancel = this.handleSidepanelCancel.bind(this);\n this.handleStartTopicRequest = this.handleStartTopicRequest.bind(this);\n this.handleNewTopicCreated = this.handleNewTopicCreated.bind(this);\n this.handleTopicUpdateRequest = this.handleTopicUpdateRequest.bind(this);\n this.handleUnarchive = this.handleUnarchive.bind(this);\n this.handleChangePermissions = this.handleChangePermissions.bind(this);\n this.handleTagsUpdateRequest = this.handleTagsUpdateRequest.bind(this);\n this.handleLogout = this.handleLogout.bind(this);\n this.handleDeleteAccount = this.handleDeleteAccount.bind(this);\n this.handleDeleteTopicRequest = this.handleDeleteTopicRequest.bind(this);\n this.handleDeleteMessagesRequest = this.handleDeleteMessagesRequest.bind(this);\n this.handleLeaveUnsubRequest = this.handleLeaveUnsubRequest.bind(this);\n this.handleBlockTopicRequest = this.handleBlockTopicRequest.bind(this);\n this.handleReportTopic = this.handleReportTopic.bind(this);\n this.handleShowContextMenu = this.handleShowContextMenu.bind(this);\n this.defaultTopicContextMenu = this.defaultTopicContextMenu.bind(this);\n this.handleHideContextMenu = this.handleHideContextMenu.bind(this);\n this.handleShowAlert = this.handleShowAlert.bind(this);\n this.handleShowInfoView = this.handleShowInfoView.bind(this);\n this.handleMemberUpdateRequest = this.handleMemberUpdateRequest.bind(this);\n this.handleValidateCredentialsRequest = this.handleValidateCredentialsRequest.bind(this);\n this.handlePasswordResetRequest = this.handlePasswordResetRequest.bind(this);\n this.handleResetPassword = this.handleResetPassword.bind(this);\n this.handleContextMenuAction = this.handleContextMenuAction.bind(this);\n this.handleShowCountrySelector = this.handleShowCountrySelector.bind(this);\n\n this.handleShowForwardDialog = this.handleShowForwardDialog.bind(this);\n this.handleHideForwardDialog = this.handleHideForwardDialog.bind(this);\n\n this.handleStartVideoCall = this.handleStartVideoCall.bind(this);\n this.handleStartAudioCall = this.handleStartAudioCall.bind(this);\n this.handleInfoMessage = this.handleInfoMessage.bind(this);\n this.handleDataMessage = this.handleDataMessage.bind(this);\n this.handleCallClose = this.handleCallClose.bind(this);\n\n this.handleCallInvite = this.handleCallInvite.bind(this);\n this.handleCallRinging = this.handleCallRinging.bind(this);\n this.handleCallHangup = this.handleCallHangup.bind(this);\n this.handleCallSendOffer = this.handleCallSendOffer.bind(this);\n this.handleCallIceCandidate = this.handleCallIceCandidate.bind(this);\n this.handleCallSendAnswer = this.handleCallSendAnswer.bind(this);\n\n this.handleCallAccept = this.handleCallAccept.bind(this);\n\n this.sendMessageToTopic = this.sendMessageToTopic.bind(this);\n\n // FIXME: this is unused.\n this.callTimeoutTimer = null;\n }\n\n getBlankState() {\n const settings = LocalStorageUtil.getObject('settings') || {};\n const persist = !!LocalStorageUtil.getObject('keep-logged-in');\n\n return {\n connected: false,\n // Connected and subscribed to 'me'\n ready: false,\n // Try to re-login on new connection.\n autoLogin: false,\n transport: settings.transport || null,\n serverAddress: settings.serverAddress || detectServerAddress(),\n secureConnection: settings.secureConnection === undefined ?\n isSecureConnection() : settings.secureConnection,\n serverVersion: \"no connection\",\n // \"On\" is the default, so saving the \"off\" state.\n messageSounds: !settings.messageSoundsOff,\n incognitoMode: false,\n // Persistent request to enable alerts.\n desktopAlerts: persist && !!settings.desktopAlerts,\n // Enable / disable checkbox.\n desktopAlertsEnabled: (isSecureConnection() || isLocalHost()) &&\n (typeof firebaseInitApp != 'undefined') && (typeof navigator != 'undefined') &&\n (typeof FIREBASE_INIT != 'undefined'),\n firebaseToken: persist ? LocalStorageUtil.getObject('firebase-token') : null,\n\n applicationVisible: !document.hidden,\n\n errorText: '',\n errorLevel: null,\n errorAction: undefined,\n errorActionText: null,\n\n sidePanelSelected: 'login',\n sidePanelTitle: null,\n sidePanelAvatar: null,\n myTrustedBadges: [],\n loadSpinnerVisible: false,\n\n login: '',\n password: '',\n persist: persist,\n myUserId: null,\n liveConnection: navigator.onLine,\n topicSelected: '',\n topicSelectedOnline: false,\n topicSelectedAcs: null,\n newTopicParams: null,\n loginDisabled: false,\n displayMobile: (window.innerWidth <= MEDIA_BREAKPOINT),\n infoPanel: undefined,\n mobilePanel: 'sidepanel',\n\n // Video calls.\n callTopic: undefined,\n callState: CALL_STATE_NONE,\n callAudioOnly: undefined,\n // If true, call state should be transitioned to CALL_STATE_IN_PROGRESS upon\n // switching to the call topic.\n callShouldStart: false,\n\n contextMenuVisible: false,\n contextMenuBounds: null,\n contextMenuClickAt: null,\n contextMenuParams: null,\n contextMenuItems: [],\n\n forwardDialogVisible: false,\n forwardMessage: null,\n\n // Modal alert dialog.\n alertVisible: false,\n alertParams: {},\n\n // Chats as shown in the ContactsView\n chatList: [],\n // Contacts returned by a search query.\n searchResults: [],\n // Merged results of a search query and p2p chats.\n searchableContacts: [],\n // Credential validation.\n reqCredMethod: undefined,\n credMethod: undefined,\n credCode: undefined,\n credToken: undefined,\n // Topic to go to after login.\n requestedTopic: undefined\n };\n }\n\n componentDidMount() {\n window.addEventListener('resize', this.handleResize);\n this.handleOnlineOn = _ => { this.handleOnline(true); }\n window.addEventListener('online', this.handleOnlineOn);\n this.handleOnlineOff = _ => { this.handleOnline(false); }\n window.addEventListener('offline', this.handleOnlineOff);\n window.addEventListener('hashchange', this.handleHashRoute);\n\n // Process background notifications from the service worker.\n if (typeof BroadcastChannel == 'function') {\n const serviceWorkerChannel = new BroadcastChannel('tinode-sw');\n serviceWorkerChannel.addEventListener('message', this.handlePushMessage);\n } else {\n // Safari is broken by design.\n console.warn(\"Your browser does not support BroadcastChannel. Some features will not be available\");\n }\n\n // Window/tab visible or invisible for pausing timers.\n document.addEventListener('visibilitychange', this.handleVisibilityEvent);\n\n this.setState({\n viewportWidth: document.documentElement.clientWidth,\n viewportHeight: document.documentElement.clientHeight\n });\n\n new Promise((resolve, reject) => {\n this.tinode = TinodeWeb.tnSetup(this.state.serverAddress, isSecureConnection(), this.state.transport,\n this.props.intl.locale, this.state.persist, resolve);\n this.tinode.onConnect = this.handleConnected;\n this.tinode.onDisconnect = this.handleDisconnect;\n this.tinode.onAutoreconnectIteration = this.handleAutoreconnectIteration;\n this.tinode.onInfoMessage = this.handleInfoMessage;\n this.tinode.onDataMessage = this.handleDataMessage;\n }).then(_ => {\n // Initialize desktop alerts.\n if (this.state.desktopAlertsEnabled) {\n this.initFCMessaging().catch(_ => {\n // do nothing: handled earlier.\n // catch needed to pervent unnecessary logging of error.\n });\n }\n\n // Read contacts from cache.\n this.resetContactList();\n\n const token = this.state.persist ? LocalStorageUtil.getObject('auth-token') : undefined;\n if (token) {\n this.setState({autoLogin: true});\n\n // When reading from storage, date is returned as string.\n token.expires = new Date(token.expires);\n this.tinode.setAuthToken(token);\n this.tinode.connect().catch(err => {\n // Socket error\n this.handleError(err.message, 'err');\n });\n }\n\n this.readTimer = null;\n this.readTimerCallback = null;\n\n // Parse the hash navigation params.\n const parsedNav = HashNavigation.parseUrlHash(window.location.hash);\n // Maybe navigate to home screen.\n if (!['cred', 'reset', 'register'].includes(parsedNav.path[0])) {\n // Save possible topic name.\n this.setState({requestedTopic: parsedNav.path[1]});\n const path = parsedNav.params && parsedNav.params.cred_done ?\n HashNavigation.addUrlParam('', 'cred_done', parsedNav.params.cred_done):\n '';\n HashNavigation.navigateTo(path);\n } else {\n this.handleHashRoute();\n }\n });\n }\n\n componentWillUnmount() {\n window.removeEventListener('resize', this.handleResize);\n window.removeEventListener('hashchange', this.handleHashRoute);\n window.removeEventListener('online', this.handleOnlineOn);\n window.removeEventListener('offline', this.handleOnlineOff);\n document.removeEventListener('visibilitychange', this.handleVisibilityEvent);\n }\n\n // Setup transport (usually websocket) and server address. This will terminate connection with the server.\n static tnSetup(serverAddress, secureConnection, transport, locale, persistentCache, onSetupCompleted) {\n const tinode = new Tinode({appName: APP_NAME, host: serverAddress, apiKey: API_KEY, transport: transport,\n secure: secureConnection, persist: persistentCache}, onSetupCompleted);\n tinode.setHumanLanguage(locale);\n tinode.enableLogging(LOGGING_ENABLED, true);\n return tinode;\n }\n\n // Tinode received a push notification from the server.\n handlePushMessage(payload) {\n this.tinode.oobNotification(payload.data || {});\n }\n\n initFCMessaging() {\n const {formatMessage, locale} = this.props.intl;\n const onError = (msg, err) => {\n console.error(msg, err);\n this.handleError(formatMessage(messages.push_init_failed), 'err');\n this.setState({firebaseToken: null});\n LocalStorageUtil.updateObject('settings', {desktopAlerts: false});\n }\n\n try {\n this.fcm = firebaseGetMessaging(firebaseInitApp(FIREBASE_INIT, APP_NAME));\n return navigator.serviceWorker.getRegistration('/service-worker.js').then(reg => {\n return reg || navigator.serviceWorker.register('/service-worker.js').then(reg => {\n this.checkForAppUpdate(reg);\n return reg;\n });\n }).then(reg => {\n // Pass locale and version config to the service worker.\n (reg.active || reg.installing).postMessage(JSON.stringify({locale: locale, version: PACKAGE_VERSION}));\n // Request token.\n return TinodeWeb.requestFCMToken(this.fcm, reg);\n }).then(token => {\n const persist = LocalStorageUtil.getObject('keep-logged-in');\n if (token != this.state.firebaseToken) {\n this.tinode.setDeviceToken(token);\n if (persist) {\n LocalStorageUtil.setObject('firebase-token', token);\n }\n }\n this.setState({firebaseToken: token, desktopAlerts: true});\n if (persist) {\n LocalStorageUtil.updateObject('settings', {desktopAlerts: true});\n }\n\n // Handhe FCM pushes\n // (a) for channels always,\n // (b) pushes when the app is in foreground but has no focus.\n firebaseOnMessage(this.fcm, payload => { this.handlePushMessage(payload); });\n }).catch(err => {\n // SW registration or FCM has failed :(\n onError(err);\n throw err;\n });\n } catch (err) {\n onError(err);\n return Promise.reject(err);\n }\n }\n\n // Google's FCM API is idiotic.\n static requestFCMToken(fcm, sw) {\n return firebaseGetToken(fcm, {\n serviceWorkerRegistration: sw,\n vapidKey: FIREBASE_INIT.messagingVapidKey\n }).then(token => {\n if (token) {\n return token;\n } else {\n // Try to request permissions.\n return Notification.requestPermission().then(permission => {\n if (permission === 'granted') {\n return firebaseGetToken(fcm, {\n serviceWorkerRegistration: reg,\n vapidKey: FIREBASE_INIT.messagingVapidKey\n }).then(token => {\n if (token) {\n return token;\n } else {\n throw new Error(\"Failed to initialize notifications\");\n }\n });\n } else {\n throw new Error(\"No permission to send notifications: \" + permission);\n }\n });\n }\n });\n }\n\n handleResize() {\n const mobile = document.documentElement.clientWidth <= MEDIA_BREAKPOINT;\n this.setState({\n viewportWidth: document.documentElement.clientWidth,\n viewportHeight: document.documentElement.clientHeight\n });\n if (this.state.displayMobile != mobile) {\n this.setState({displayMobile: mobile});\n }\n }\n\n // Check if a newer version of TinodeWeb app is available at the server.\n checkForAppUpdate(reg) {\n reg.onupdatefound = _ => {\n const installingWorker = reg.installing;\n installingWorker.onstatechange = _ => {\n if (installingWorker.state == 'installed' && navigator.serviceWorker.controller) {\n const msg = <>\n \n \n .;\n this.handleError(msg, 'info');\n }\n }\n }\n }\n\n // Handle for hash navigation (hashchange) event: update state.\n handleHashRoute() {\n const hash = HashNavigation.parseUrlHash(window.location.hash);\n // Start with panel parameters.\n const newState = {\n infoPanel: hash.params.info,\n newTopicTabSelected: hash.params.tab\n };\n\n if (hash.path && hash.path.length > 0) {\n // Left-side panel selector.\n if (['register','settings','edit','notif','security','support','general','crop',\n 'cred','reset','newtpk','archive','blocked','contacts',''].includes(hash.path[0])) {\n newState.sidePanelSelected = hash.path[0];\n } else {\n console.warn(\"Unknown sidepanel view\", hash.path[0]);\n }\n\n // Topic for MessagesView selector.\n let topicName = hash.path[1] || null;\n if (topicName != this.state.topicSelected) {\n if (!Tinode.topicType(topicName)) {\n // Clear invalid topic name and hide messages view on mobile.\n topicName = null;\n newState.mobilePanel = 'sidepanel';\n } else {\n // Topic valid: show messages view on mobile.\n newState.mobilePanel = 'topic-view';\n }\n Object.assign(newState, {\n topicSelected: topicName,\n topicSelectedAcs: this.tinode.getTopicAccessMode(topicName)\n });\n }\n } else {\n // Empty hashpath\n Object.assign(newState, {sidePanelSelected: '', topicSelected: null});\n }\n\n // Save credential validation parameters, if available.\n if (hash.params.method) {\n newState.credMethod = hash.params.method;\n }\n if (hash.params.code) {\n newState.credCode = hash.params.code;\n }\n if (hash.params.token) {\n newState.credToken = hash.params.token;\n }\n\n // Show a message if validation was successful.\n if (hash.params.cred_done) {\n Object.assign(newState,\n TinodeWeb.stateForError(this.props.intl.formatMessage(messages.cred_confirmed_successfully), 'info'));\n }\n\n this.setState(newState);\n }\n\n handleOnline(online) {\n if (online) {\n this.handleError();\n clearInterval(this.reconnectCountdown);\n this.tinode.reconnect();\n } else {\n this.handleError(this.props.intl.formatMessage(messages.no_connection), 'warn');\n }\n this.setState({liveConnection: online});\n }\n\n handleVisibilityEvent() {\n this.setState({applicationVisible: !document.hidden});\n }\n\n static stateForError(err, level, action, actionText) {\n return {\n errorText: err,\n errorLevel: level,\n errorAction: action,\n errorActionText: actionText,\n callShouldStart: false,\n };\n }\n\n handleError(err, level, action, actionText) {\n this.setState(TinodeWeb.stateForError(err, level, action, actionText));\n }\n\n // User clicked Login button in the side panel.\n handleLoginRequest(login, password) {\n this.setState({\n loginDisabled: true,\n login: login,\n password: password,\n loadSpinnerVisible: true,\n autoLogin: true\n });\n this.handleError('', null);\n\n if (this.tinode.isConnected()) {\n this.doLogin(login, password, null, {meth: this.state.credMethod, resp: this.state.credCode});\n } else {\n this.tinode.connect().catch(err => {\n // Socket error\n this.setState({loginDisabled: false, autoLogin: false, loadSpinnerVisible: false});\n this.handleError(err.message, 'err');\n });\n }\n\n if (this.state.desktopAlertsEnabled && !this.state.firebaseToken) {\n // Firefox and Safari: \"The Notification permission may only be requested from inside a\n // short running user-generated event handler\".\n this.initFCMessaging();\n }\n }\n\n // Enable or disable saving the password and IndexedDB.\n handlePersistenceChange(persist) {\n if (persist) {\n this.tinode.initStorage().then(_ => {\n LocalStorageUtil.setObject('keep-logged-in', true);\n this.setState({persist: true});\n });\n } else {\n this.tinode.clearStorage().then(_ => {\n LocalStorageUtil.setObject('keep-logged-in', false);\n this.setState({persist: false});\n });\n }\n }\n\n // Connection succeeded.\n handleConnected() {\n // Just to be sure.\n clearInterval(this.reconnectCountdown);\n this.handleError();\n\n const params = this.tinode.getServerInfo();\n this.setState({\n serverVersion: params.ver + ' ' + (params.build ? params.build : 'none'),\n // \"reqCred\":{\"auth\":[\"email\"]}\n reqCredMethod: ((params.reqCred || {}).auth || [])[0] || 'email'\n });\n\n if (this.state.autoLogin) {\n this.doLogin(this.state.login, this.state.password, null,\n {meth: this.state.credMethod, resp: this.state.credCode});\n }\n }\n\n // Called for each auto-reconnect iteration.\n handleAutoreconnectIteration(sec, prom) {\n clearInterval(this.reconnectCountdown);\n\n if (sec < 0) {\n // Clear error\n this.handleError();\n return;\n }\n\n if (prom) {\n // Reconnecting now\n prom.then(_ => {\n // Reconnected: clear error\n this.handleError();\n }).catch(err => {\n this.handleError(err.message, 'err');\n });\n return;\n }\n\n const {formatMessage} = this.props.intl;\n let count = sec / 1000;\n count = count | count;\n this.reconnectCountdown = setInterval(_ => {\n if (count < -10) {\n // Count could go to negative if computer woke up from sleep.\n clearInterval(this.reconnectCountdown);\n this.tinode.reconnect();\n return;\n }\n\n const fmtTime = (count > 99) ? secondsToTime(count) : count;\n this.handleError(\n formatMessage(messages.reconnect_countdown, {seconds: fmtTime}),\n 'warn',\n _ => {\n clearInterval(this.reconnectCountdown);\n this.tinode.reconnect();\n },\n formatMessage(messages.reconnect_now)\n );\n count -= 1;\n }, 1000);\n }\n\n // Connection lost\n handleDisconnect(err) {\n this.setState({\n connected: false,\n ready: false,\n topicSelectedOnline: false,\n errorText: err && err.message ? err.message : \"Disconnected\",\n errorLevel: err && err.message ? 'err' : 'warn',\n loginDisabled: false,\n contextMenuVisible: false,\n forwardDialogVisible: false,\n serverVersion: \"no connection\"\n });\n }\n\n doLogin(login, password, tmpToken, cred) {\n if (this.tinode.isAuthenticated()) {\n // Already logged in. Go to default screen.\n HashNavigation.navigateTo('');\n return;\n }\n\n let token = tmpToken || (this.tinode.getAuthToken() || {}).token;\n if (!(login && password) && !token) {\n // No login credentials provided.\n // Make sure we are on the login page.\n HashNavigation.navigateTo('');\n this.setState({loginDisabled: false});\n return;\n }\n\n // Sanitize and package credentail.\n cred = Tinode.credential(cred);\n // May be disconnected.\n let connectionPromise = this.tinode.isConnected() ? Promise.resolve() : this.tinode.connect();\n // Try to login with login/password. If they are not available, try token; if no token, ask for login/password.\n let loginPromise;\n if (login && password) {\n token = null;\n this.setState({password: null});\n loginPromise = connectionPromise.then(_ => this.tinode.loginBasic(login, password, cred));\n } else {\n loginPromise = connectionPromise.then(_ => this.tinode.loginToken(token, cred));\n }\n\n loginPromise.then(ctrl => {\n if (ctrl.code >= 300 && ctrl.text === 'validate credentials') {\n this.setState({loadSpinnerVisible: false});\n if (cred) {\n this.handleError(this.props.intl.formatMessage(messages.code_doesnot_match), 'warn');\n }\n TinodeWeb.navigateToCredentialsView(ctrl.params);\n } else {\n this.handleLoginSuccessful();\n }\n }).catch(err => {\n const autoLogin = err.code >= 500;\n // Connection or login failed, report error.\n this.setState({\n loginDisabled: false,\n credMethod: undefined,\n credCode: undefined,\n loadSpinnerVisible: false,\n autoLogin: autoLogin\n });\n this.handleError(err.message, 'err');\n console.warn(\"Login failed\", err);\n if (!autoLogin) {\n if (token) {\n this.handleLogout();\n }\n HashNavigation.navigateTo('');\n }\n });\n }\n\n static navigateToCredentialsView(params) {\n const parsed = HashNavigation.parseUrlHash(window.location.hash);\n parsed.path[0] = 'cred';\n parsed.params['method'] = params.cred[0];\n parsed.params['token'] = params.token;\n HashNavigation.navigateTo(HashNavigation.composeUrlHash(parsed.path, parsed.params));\n }\n\n handleLoginSuccessful() {\n this.handleError();\n\n // Refresh authentication token.\n if (LocalStorageUtil.getObject('keep-logged-in')) {\n LocalStorageUtil.setObject('auth-token', this.tinode.getAuthToken());\n }\n\n const goToTopic = this.state.requestedTopic;\n // Logged in fine, subscribe to 'me' attaching callbacks from the contacts view.\n const me = this.tinode.getMeTopic();\n me.onMetaDesc = this.tnMeMetaDesc;\n me.onContactUpdate = this.tnMeContactUpdate;\n me.onSubsUpdated = this.tnMeSubsUpdated;\n this.setState({\n connected: true,\n credMethod: undefined,\n credCode: undefined,\n credToken: undefined,\n myUserId: this.tinode.getCurrentUserID(),\n autoLogin: true,\n requestedTopic: undefined,\n });\n // Subscribe, fetch topic desc, the list of subscriptions. Messages are not fetched.\n me.subscribe(\n me.startMetaQuery().\n withLaterSub().\n withDesc().\n withTags().\n withCred().\n build()\n ).catch(err => {\n this.tinode.disconnect();\n localStorage.removeItem('auth-token');\n this.handleError(err.message, 'err');\n HashNavigation.navigateTo('');\n }).finally(_ => {\n this.setState({loadSpinnerVisible: false});\n });\n let urlHash = HashNavigation.setUrlSidePanel(window.location.hash, 'contacts');\n if (goToTopic) {\n urlHash = HashNavigation.setUrlTopic(urlHash, goToTopic);\n }\n HashNavigation.navigateTo(urlHash);\n }\n\n tnMeMetaDesc(desc) {\n if (desc) {\n if (desc.public) {\n this.setState({\n sidePanelTitle: desc.public.fn,\n sidePanelAvatar: makeImageUrl(desc.public.photo)\n });\n }\n if (desc.trusted) {\n const badges = [];\n for (const [key, val] of Object.entries(desc.trusted)) {\n if (val) {\n badges.push(key);\n }\n }\n this.setState({\n myTrustedBadges: badges,\n });\n }\n if (desc.acs) {\n this.setState({\n incognitoMode: !desc.acs.isPresencer()\n });\n }\n }\n }\n\n // Reactions to updates to the contact list.\n tnMeContactUpdate(what, cont) {\n if (what == 'on' || what == 'off') {\n this.resetContactList();\n if (this.state.topicSelected == cont.topic) {\n this.setState({topicSelectedOnline: (what == 'on')});\n }\n } else if (what == 'read') {\n this.resetContactList();\n } else if (what == 'msg') {\n // Check if the topic is archived. If so, don't play a sound.\n const topic = this.tinode.getTopic(cont.topic);\n const archived = topic && topic.isArchived();\n\n // New message received. Maybe the message is from the current user, then unread is 0.\n if (cont.unread > 0 && this.state.messageSounds && !archived) {\n // Skip update if the topic is currently open, otherwise the badge will annoyingly flash.\n if (document.hidden || this.state.topicSelected != cont.topic) {\n POP_SOUND.play().catch(_ => {\n // play() throws if the user did not click the app first: https://goo.gl/xX8pDD.\n });\n }\n }\n // Reorder contact list to use possibly updated 'touched'.\n this.resetContactList();\n } else if (what == 'recv') {\n // Explicitly ignoring \"recv\" -- it causes no visible updates to contact list.\n } else if (what == 'gone' || what == 'unsub') {\n // Topic deleted or user unsubscribed. Remove topic from view.\n // If the currently selected topic is gone, clear the selection.\n if (this.state.topicSelected == cont.topic) {\n this.handleTopicSelected(null);\n }\n // Redraw without the deleted topic.\n this.resetContactList();\n } else if (what == 'acs') {\n // Permissions changed. If it's for the currently selected topic,\n // update the views.\n if (this.state.topicSelected == cont.topic) {\n this.setState({topicSelectedAcs: cont.acs});\n }\n } else if (what == 'del') {\n // TODO: messages deleted (hard or soft) -- update pill counter.\n } else if (what == 'upd' || what == 'call') {\n // upd, call - handled by the SDK. Explicitly ignoring here.\n } else {\n // TODO(gene): handle other types of notifications:\n // * ua -- user agent changes (maybe display a pictogram for mobile/desktop).\n console.info(\"Unsupported (yet) presence update:\", what, \"in\", cont.topic);\n }\n }\n\n tnMeSubsUpdated(unused) {\n this.resetContactList();\n }\n\n // Merge search results and contact list to create a single flat\n // list of known contacts for GroupManager to use.\n static prepareSearchableContacts(chatList, foundContacts) {\n const merged = {};\n\n // For chatList topics merge only p2p topics and convert them to the\n // same format as foundContacts.\n for (const c of chatList) {\n if (Tinode.isP2PTopicName(c.topic)) {\n merged[c.topic] = {\n user: c.topic,\n updated: c.updated,\n public: c.public,\n private: c.private,\n acs: c.acs\n };\n }\n }\n\n // Add all foundCountacts if they have not been added already.\n for (const c of foundContacts) {\n if (!merged[c.user]) {\n merged[c.user] = c;\n }\n }\n\n return Object.values(merged);\n }\n\n resetContactList() {\n const newState = {\n chatList: []\n };\n\n if (!this.state.ready) {\n newState.ready = true;\n }\n\n this.tinode.getMeTopic().contacts((c) => {\n if (!c.topic && !c.user) {\n // Contacts expect c.topic to be set.\n c.topic = c.name;\n }\n\n newState.chatList.push(c);\n if (this.state.topicSelected == c.topic) {\n newState.topicSelectedOnline = c.online;\n newState.topicSelectedAcs = c.acs;\n }\n });\n\n const past = new Date(0);\n newState.chatList.sort((a, b) => {\n return (a.touched || past).getTime() - (b.touched || past).getTime();\n });\n\n // Merge search results and chat list.\n newState.searchableContacts = TinodeWeb.prepareSearchableContacts(newState.chatList, this.state.searchResults);\n this.setState(newState);\n }\n\n /* Fnd topic: find contacts by tokens */\n tnInitFind() {\n const fnd = this.tinode.getFndTopic();\n fnd.onSubsUpdated = this.tnFndSubsUpdated;\n if (fnd.isSubscribed()) {\n this.tnFndSubsUpdated();\n } else {\n fnd.subscribe(fnd.startMetaQuery().withSub().build()).catch(err => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n tnFndSubsUpdated() {\n const foundContacts = [];\n // Don't attempt to create P2P topics which already exist. Server will reject the duplicates.\n this.tinode.getFndTopic().contacts((s) => {\n foundContacts.push(s);\n });\n this.setState({\n searchResults: foundContacts,\n searchableContacts: TinodeWeb.prepareSearchableContacts(this.state.chatList, foundContacts)\n });\n }\n\n /** Called when the user enters a contact into the contact search field in the NewAccount panel\n @param query {Array} is an array of contacts to search for\n */\n handleSearchContacts(query) {\n const fnd = this.tinode.getFndTopic();\n fnd.setMeta({desc: {public: query}})\n .then(_ => fnd.getMeta(fnd.startMetaQuery().withSub().build()))\n .catch(err => this.handleError(err.message, 'err'));\n }\n\n // User clicked on a topic in the side panel or deleted a topic.\n handleTopicSelected(topicName) {\n // Clear newTopicParams after use.\n if (this.state.newTopicParams && this.state.newTopicParams._topicName != topicName) {\n this.setState({\n newTopicParams: null\n });\n }\n\n if (topicName) {\n this.setState({\n errorText: '',\n errorLevel: null,\n mobilePanel: 'topic-view',\n infoPanel: undefined\n });\n // Different topic selected.\n if (this.state.topicSelected != topicName) {\n this.setState({\n topicSelectedOnline: this.tinode.isTopicOnline(topicName),\n topicSelectedAcs: this.tinode.getTopicAccessMode(topicName),\n forwardMessage: null\n });\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', topicName));\n }\n } else {\n // Currently selected contact deleted\n this.setState({\n errorText: '',\n errorLevel: null,\n mobilePanel: 'sidepanel',\n topicSelectedOnline: false,\n topicSelectedAcs: null,\n infoPanel: undefined,\n forwardMessage: null\n });\n\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', null));\n }\n }\n\n // In mobile view user requested to show sidepanel\n handleHideMessagesView() {\n this.setState({\n mobilePanel: 'sidepanel'\n });\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, null));\n }\n\n // User is sending a message, either plain text or a drafty object, possibly\n // with attachments.\n // - msg - Drafty message with content\n // - promise - Promise to be resolved when the upload is completed\n // - uploadCompletionPromise - for tracking progress\n // - head - head dictionary to be attached to the message\n handleSendMessage(msg, uploadCompletionPromise, uploader, head) {\n const topic = this.tinode.getTopic(this.state.topicSelected);\n /* TODO: check if return is required */\n return this.sendMessageToTopic(topic, msg, uploadCompletionPromise, uploader, head);\n }\n\n sendMessageToTopic(topic, msg, uploadCompletionPromise, uploader, head) {\n msg = topic.createMessage(msg, false);\n // The uploader is used to show progress.\n msg._uploader = uploader;\n\n if (head) {\n msg.head = Object.assign(msg.head || {}, head);\n }\n\n const completion = [];\n if (uploadCompletionPromise) {\n completion.push(uploadCompletionPromise);\n }\n\n if (!topic.isSubscribed()) {\n // Topic is not subscribed yet. Subscribe.\n const subscribePromise =\n topic.subscribe()\n .then(_ => {\n // If there are unsent messages (except video call messages),\n // try sending them now. Unsent video call messages will be dropped.\n let calls = [];\n topic.queuedMessages(pub => {\n if (pub._sending || pub.seq == msg.seq) {\n return;\n }\n if (pub.head && pub.head.webrtc) {\n // Filter out unsent video call messages.\n calls.push(pub.seq);\n return;\n }\n if (topic.isSubscribed()) {\n topic.publishMessage(pub);\n }\n });\n if (calls.length > 0) {\n topic.delMessagesList(calls, true);\n }\n });\n completion.push(subscribePromise);\n }\n\n // TODO: check if return is required.\n return topic.publishDraft(msg, Promise.all(completion))\n .then(ctrl => {\n if (topic.isArchived()) {\n topic.archive(false);\n }\n return ctrl;\n })\n .catch(err => this.handleError(err.message, 'err'));\n }\n\n handleNewChatInvitation(topicName, action) {\n const topic = this.tinode.getTopic(topicName);\n let response = null;\n switch (action) {\n case 'accept':\n // Accept given permissions.\n const mode = topic.getAccessMode().getGiven();\n response = topic.setMeta({sub: {mode: mode}});\n if (topic.isP2PType()) {\n // For P2P topics change 'given' permission of the peer too.\n // In p2p topics the other user has the same name as the topic.\n response = response.then(_ => topic.setMeta({sub: {user: topicName, mode: mode}}));\n }\n break;\n case 'delete':\n // Ignore invitation by deleting it.\n response = topic.delTopic(true);\n break;\n case 'block':\n // Ban the topic making futher invites impossible.\n // Just self-ban.\n const am = topic.getAccessMode().updateWant('-JP').getWant();\n response = topic.setMeta({sub: {mode: am}}).then(_ => this.handleTopicSelected(null));\n break;\n default:\n console.warn(\"Unknown invitation action\", '\"' + action + '\"\"');\n }\n\n if (response != null) {\n response.catch(err => this.handleError(err.message, 'err'));\n }\n }\n\n // User chose a Sign Up menu item.\n handleNewAccount() {\n this.handleError();\n\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash, 'register'));\n }\n\n // Actual registration of a new account.\n handleNewAccountRequest(login_, password_, public_, cred_, tags_) {\n // Clear old error, if any.\n this.handleError();\n\n this.tinode.connect(this.state.serverAddress)\n .then(_ => {\n let attachments;\n if (public_ && public_.photo && public_.photo.ref) {\n attachments = [public_.photo.ref];\n }\n return this.tinode.createAccountBasic(login_, password_,\n {public: public_, tags: tags_, cred: Tinode.credential(cred_), attachments: attachments});\n }).then(ctrl => {\n if (ctrl.code >= 300 && ctrl.text == 'validate credentials') {\n TinodeWeb.navigateToCredentialsView(ctrl.params);\n } else {\n this.handleLoginSuccessful(this);\n }\n }).catch(err => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleToggleIncognitoMode(on) {\n // Make state undefined.\n this.setState({incognitoMode: null});\n\n const me = this.tinode.getMeTopic();\n const am = me.getAccessMode().updateWant(on ? '-P' : '+P').getWant();\n me.setMeta({sub: {mode: am}}).catch(err => {\n // Request failed, keep existing state.\n this.setState({incognitoMode: !on});\n this.handleError(err.message, 'err');\n });\n }\n\n handleUpdateAccountTagsRequest(_, tags) {\n this.tinode.getMeTopic().setMeta({tags: tags})\n .catch(err => this.handleError(err.message, 'err'));\n }\n\n // User chose Settings menu item.\n handleSettings() {\n this.handleError();\n\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash,\n this.state.myUserId ? 'edit' : 'settings'));\n }\n\n // User updated global parameters.\n handleGlobalSettings(settings) {\n const serverAddress = settings.serverAddress || this.state.serverAddress;\n const transport = settings.transport || this.state.transport;\n const secureConnection = settings.secureConnection === undefined ?\n this.state.secureConnection : settings.secureConnection;\n if (this.tinode) {\n this.tinode.clearStorage();\n this.tinode.onDisconnect = undefined;\n this.tinode.disconnect();\n }\n this.tinode = TinodeWeb.tnSetup(serverAddress, secureConnection, transport,\n this.props.intl.locale, LocalStorageUtil.getObject('keep-logged-in'));\n this.tinode.onConnect = this.handleConnected;\n this.tinode.onDisconnect = this.handleDisconnect;\n this.tinode.onAutoreconnectIteration = this.handleAutoreconnectIteration;\n this.tinode.onInfoMessage = this.handleInfoMessage;\n this.tinode.onDataMessage = this.handleDataMessage;\n\n this.setState({\n serverAddress: serverAddress,\n transport: transport,\n secureConnection: secureConnection,\n });\n LocalStorageUtil.setObject('settings', {\n serverAddress: serverAddress,\n transport: transport,\n secureConnection: secureConnection,\n });\n\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash, ''));\n }\n\n // User chose 'Archived chats'.\n handleShowArchive() {\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash,\n this.state.myUserId ? 'archive' : ''));\n }\n\n // User viewes 'Blocked chats'.\n handleShowBlocked() {\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash,\n this.state.myUserId ? 'blocked' : ''));\n }\n\n toggleFCMToken(enabled) {\n if (enabled) {\n this.setState({desktopAlerts: null});\n if (!this.state.firebaseToken) {\n this.initFCMessaging();\n } else {\n this.setState({desktopAlerts: true});\n if (LocalStorageUtil.getObject('keep-logged-in')) {\n LocalStorageUtil.updateObject('settings', {desktopAlerts: true});\n }\n }\n } else if (this.state.firebaseToken && this.fcm) {\n firebaseDelToken(this.fcm).catch(err => {\n console.error(\"Unable to delete token.\", err);\n }).finally(_ => {\n LocalStorageUtil.updateObject('settings', {desktopAlerts: false});\n localStorage.removeItem('firebase-token');\n this.setState({desktopAlerts: false, firebaseToken: null});\n // Inform the server that the token was deleted.\n this.tinode.setDeviceToken(null);\n });\n } else {\n this.setState({desktopAlerts: false, firebaseToken: null});\n LocalStorageUtil.updateObject('settings', {desktopAlerts: false});\n }\n }\n\n handleToggleMessageSounds(enabled) {\n this.setState({messageSounds: enabled});\n LocalStorageUtil.updateObject('settings', {\n messageSoundsOff: !enabled\n });\n }\n\n handleCredAdd(method, value) {\n const me = this.tinode.getMeTopic();\n me.setMeta({cred: {meth: method, val: value}})\n .catch(err => this.handleError(err.message, 'err'));\n }\n\n handleCredDelete(method, value) {\n const me = this.tinode.getMeTopic();\n me.delCredential(method, value)\n .catch(err => this.handleError(err.message, 'err'));\n }\n\n handleCredConfirm(method, response) {\n TinodeWeb.navigateToCredentialsView({cred: [method]});\n }\n\n // User clicked Cancel button in Setting or Sign Up panel.\n handleSidepanelCancel() {\n const parsed = HashNavigation.parseUrlHash(window.location.hash);\n let path = '';\n if (['security','support','general','notif'].includes(parsed.path[0])) {\n path = 'edit';\n } else if ('crop' == parsed.path[0]) {\n path = 'general';\n } else if ('blocked' == parsed.path[0]) {\n path = 'security';\n } else if (this.state.myUserId) {\n path = 'contacts';\n }\n parsed.path[0] = path;\n if (parsed.params) {\n delete parsed.params.code;\n delete parsed.params.method;\n delete parsed.params.tab;\n delete parsed.params.scheme;\n delete parsed.params.token;\n }\n HashNavigation.navigateTo(HashNavigation.composeUrlHash(parsed.path, parsed.params));\n this.setState({errorText: '', errorLevel: null});\n }\n\n // Sidepanel navigator. No need to bind to 'this'.\n basicNavigator(hash) {\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash, hash));\n }\n\n // Topic info navigator. No need to bind to 'this'.\n infoNavigator(hash) {\n HashNavigation.navigateTo(HashNavigation.setUrlInfoPanel(window.location.hash, hash));\n }\n\n // Request to start a topic, new or selected from search results, or \"by ID\".\n handleStartTopicRequest(topicName, newTopicParams, isChannel) {\n // Check if topic is indeed new. If not, launch it.\n if (topicName && this.tinode.isTopicCached(topicName)) {\n this.handleTopicSelected(topicName);\n return;\n }\n\n const params = {};\n if (Tinode.isP2PTopicName(topicName)) {\n // Because we are initialing the subscription, set 'want' to all permissions.\n params.sub = {mode: DEFAULT_P2P_ACCESS_MODE};\n // Give the other user all permissions too.\n params.desc = {defacs: {auth: DEFAULT_P2P_ACCESS_MODE}};\n } else {\n topicName = topicName || this.tinode.newGroupTopicName(isChannel);\n if (newTopicParams) {\n params.desc = {public: newTopicParams.public, private: {comment: newTopicParams.private}};\n params.tags = newTopicParams.tags;\n }\n }\n params._topicName = topicName;\n this.setState({newTopicParams: params}, _ => {this.handleTopicSelected(topicName)});\n }\n\n // New topic was created, here is the new topic name.\n handleNewTopicCreated(oldName, newName) {\n let nextState = {};\n if (this.state.callShouldStart) {\n nextState = {callState: CALL_STATE_IN_PROGRESS, callShouldStart: false};\n }\n if (this.state.topicSelected == oldName && oldName != newName) {\n // If the current URl contains the old topic name, replace it with new.\n // Update the name of the selected topic first so the navigator doen't clear\n // the state.\n nextState.topicSelected = newName;\n }\n this.setState(nextState, _ => {\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', newName));\n });\n }\n\n handleTopicUpdateRequest(topicName, pub, priv, defacs) {\n this.handleError();\n\n const topic = this.tinode.getTopic(topicName);\n if (topic) {\n const params = {};\n let attachments;\n if (pub) {\n if (pub.photo) {\n if (pub.photo.ref && pub.photo.ref != Tinode.DEL_CHAR) {\n attachments = [pub.photo.ref];\n } else if (!pub.photo.data || pub.photo.data == Tinode.DEL_CHAR) {\n pub.photo = Tinode.DEL_CHAR;\n }\n }\n params.public = pub;\n }\n\n if (typeof priv == 'string') {\n params.private = (priv === Tinode.DEL_CHAR) ?\n Tinode.DEL_CHAR : {comment: priv};\n }\n if (defacs) {\n params.defacs = defacs;\n }\n topic.setMeta({desc: params, attachments: attachments})\n .catch(err => this.handleError(err.message, 'err'));\n }\n }\n\n handleUnarchive(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (topic) {\n topic.archive(false).catch(err => this.handleError(err.message, 'err'));\n }\n }\n\n handleUpdatePasswordRequest(password) {\n this.handleError();\n\n if (password) {\n this.tinode.updateAccountBasic(null, this.tinode.getCurrentLogin(), password)\n .catch(err => this.handleError(err.message, 'err'));\n }\n }\n\n handleChangePermissions(topicName, mode, uid) {\n const topic = this.tinode.getTopic(topicName);\n if (topic) {\n const am = topic.getAccessMode();\n if (uid) {\n am.updateGiven(mode);\n mode = am.getGiven();\n } else {\n am.updateWant(mode);\n mode = am.getWant();\n }\n topic.setMeta({sub: {user: uid, mode: mode}})\n .catch(err => this.handleError(err.message, 'err'));\n }\n }\n\n handleTagsUpdateRequest(topicName, tags) {\n const topic = this.tinode.getTopic(topicName);\n if (topic) {\n topic.setMeta({tags: tags})\n .catch(err => this.handleError(err.message, 'err'));\n }\n }\n\n handleLogout() {\n updateFavicon(0);\n\n // Remove stored data.\n localStorage.removeItem('auth-token');\n localStorage.removeItem('firebase-token');\n localStorage.removeItem('settings');\n if (this.state.firebaseToken) {\n firebaseDelToken(this.fcm);\n }\n\n clearInterval(this.reconnectCountdown);\n\n let cleared;\n if (this.tinode) {\n cleared = this.tinode.clearStorage();\n this.tinode.onDisconnect = undefined;\n this.tinode.disconnect();\n } else {\n cleared = Promose.resolve();\n }\n this.setState(this.getBlankState());\n\n cleared.then(_ => {\n this.tinode = TinodeWeb.tnSetup(this.state.serverAddress, isSecureConnection(),\n this.state.transport, this.props.intl.locale, LocalStorageUtil.getObject('keep-logged-in'), _ => {\n this.tinode.onConnect = this.handleConnected;\n this.tinode.onDisconnect = this.handleDisconnect;\n this.tinode.onAutoreconnectIteration = this.handleAutoreconnectIteration;\n this.tinode.onInfoMessage = this.handleInfoMessage;\n this.tinode.onDataMessage = this.handleDataMessage;\n HashNavigation.navigateTo('');\n })\n });\n }\n\n handleDeleteAccount() {\n this.tinode.delCurrentUser(true).then(_ => {\n this.handleLogout();\n });\n }\n\n handleDeleteTopicRequest(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n // Request to hard-delete topic.\n topic.delTopic(true).then(_ => {\n // Hide MessagesView and InfoView panels.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, ''));\n }).catch(err => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleDeleteMessagesRequest(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n // Request hard-delete all messages.\n topic.delMessagesAll(true)\n .catch(err => this.handleError(err.message, 'err'));\n }\n\n handleLeaveUnsubRequest(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n topic.leave(true).then(_ => {\n // Hide MessagesView and InfoView panels.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, ''));\n }).catch(err => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleBlockTopicRequest(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n topic.updateMode(null, '-JP')\n .then(_ => {\n // Hide MessagesView and InfoView panels.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, ''));\n })\n .catch(err => this.handleError(err.message, 'err'));\n }\n\n handleReportTopic(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n // Publish spam report.\n this.tinode.report('report', topicName);\n\n // Remove J and P permissions.\n topic.updateMode(null, '-JP')\n .then(_ => {\n // Hide MessagesView and InfoView panels.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, ''));\n })\n .catch(err => this.handleError(err.message, 'err'));\n }\n\n handleShowContextMenu(params, menuItems) {\n this.setState({\n contextMenuVisible: true,\n contextMenuClickAt: {x: params.x, y: params.y},\n contextMenuParams: params,\n contextMenuItems: menuItems || this.defaultTopicContextMenu(params.topicName),\n contextMenuBounds: this.selfRef.current.getBoundingClientRect()\n });\n }\n\n //\n handleShowForwardDialog(params) {\n if (this.state.sidePanelSelected == 'newtpk') {\n // If the Find panel is active, close it.\n this.handleSidepanelCancel();\n }\n const header = '➦ ' + params.userName;\n const content = typeof params.content == 'string' ? Drafty.init(params.content) : Drafty.forwardedContent(params.content);\n const preview = Drafty.preview(content, FORWARDED_PREVIEW_LENGTH, true);\n const msg = Drafty.append(Drafty.appendLineBreak(Drafty.mention(header, params.userFrom)), content);\n const msgPreview = Drafty.quote(header, params.userFrom, preview);\n\n const head = {\n forwarded: params.topicName + ':' + params.seq\n };\n this.setState({\n forwardDialogVisible: true,\n forwardMessage: { head: head, msg: msg, preview: msgPreview }\n });\n }\n\n defaultTopicContextMenu(topicName) {\n const topic = this.tinode.getTopic(topicName);\n\n if (topic._deleted) {\n return [\n 'topic_delete'\n ];\n }\n\n let muted = false, blocked = false, self_blocked = false, subscribed = false, deleter = false,\n archived = false, webrtc = false;\n if (topic) {\n subscribed = topic.isSubscribed();\n archived = topic.isArchived();\n\n const acs = topic.getAccessMode();\n if (acs) {\n muted = acs.isMuted();\n blocked = !acs.isJoiner();\n self_blocked = !acs.isJoiner('want');\n deleter = acs.isDeleter();\n }\n }\n\n webrtc = !!this.tinode.getServerParam('iceServers');\n\n return [\n subscribed ? {\n title: this.props.intl.formatMessage(messages.menu_item_info),\n handler: this.handleShowInfoView\n } : null,\n subscribed && Tinode.isP2PTopicName(topicName) && webrtc ? {\n title: this.props.intl.formatMessage(messages.menu_item_audio_call),\n handler: this.handleStartAudioCall\n } : null,\n subscribed && Tinode.isP2PTopicName(topicName) && webrtc ? {\n title: this.props.intl.formatMessage(messages.menu_item_video_call),\n handler: this.handleStartVideoCall\n } : null,\n subscribed ? 'messages_clear' : null,\n subscribed && deleter ? 'messages_clear_hard' : null,\n muted ? (blocked ? null : 'topic_unmute') : 'topic_mute',\n self_blocked ? 'topic_unblock' : 'topic_block',\n archived ? 'topic_restore' : 'topic_archive',\n 'topic_delete'\n ];\n }\n\n handleHideContextMenu() {\n this.setState({\n contextMenuVisible: false,\n contextMenuClickAt: null,\n contextMenuParams: null,\n contextMenuBounds: null\n });\n }\n\n handleHideForwardDialog(keepForwardedMessage) {\n this.setState({\n forwardDialogVisible: false,\n forwardMessage: keepForwardedMessage ? this.state.forwardMessage : null\n });\n }\n\n handleContextMenuAction(action, promise, params) {\n if (action == 'topic_archive') {\n if (promise && params.topicName && params.topicName == this.state.topicSelected) {\n promise.then(_ => {\n this.handleTopicSelected(null);\n });\n }\n } else if (action == 'menu_item_forward') {\n this.handleShowForwardDialog(params);\n }\n }\n\n handleShowAlert(title, content, onConfirm, confirmText, onReject, rejectText) {\n this.setState({\n alertVisible: true,\n alertParams: {\n title: title,\n content: content,\n onConfirm: onConfirm,\n confirm: confirmText,\n onReject: onReject,\n reject: rejectText\n }\n });\n }\n\n handleShowInfoView() {\n HashNavigation.navigateTo(HashNavigation.addUrlParam(window.location.hash, 'info', 'info'));\n this.setState({infoPanel: 'info'});\n }\n\n handleMemberUpdateRequest(topicName, added, removed) {\n if (!topicName) {\n return;\n }\n\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n if (added && added.length > 0) {\n added.forEach(uid => {\n topic.invite(uid, null)\n .catch(err => this.handleError(err.message, 'err'));\n });\n }\n\n if (removed && removed.length > 0) {\n removed.forEach(uid => {\n topic.delSubscription(uid)\n .catch(err => this.handleError(err.message, 'err'));\n });\n }\n }\n\n handleValidateCredentialsRequest(cred, code, token) {\n if (this.tinode.isAuthenticated()) {\n // Adding new email or phone number in account setting.\n this.tinode.getMeTopic().setMeta({cred: {meth: cred, resp: code}})\n .catch(err => this.handleError(err.message, 'err'));\n } else {\n // Credential validation on signup.\n this.setState({credMethod: cred, credCode: code, credToken: token});\n this.doLogin(null, null, token, {meth: cred, resp: code});\n }\n }\n\n handlePasswordResetRequest(method, value) {\n // If already connected, connnect() will return a resolved promise.\n return this.tinode.connect()\n .then(_ => this.tinode.requestResetAuthSecret('basic', method, value))\n .catch(err => {\n // Socket error\n this.handleError(err.message, 'err');\n });\n }\n\n handleResetPassword(newPassword, tempAuth) {\n const secret = base64ReEncode(tempAuth.secret);\n if (!secret || !tempAuth.scheme) {\n this.handleError(this.props.intl.formatMessage(messages.invalid_security_token), 'err');\n } else {\n this.tinode.connect()\n .then(_ => this.tinode.updateAccountBasic(null, null, newPassword, {scheme: tempAuth.scheme, secret: secret}))\n .then(_ => HashNavigation.navigateTo(''))\n .catch(err => {\n // Socket error\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleShowCountrySelector(code, dial, selectedCallback) {\n this.handleShowAlert(\"Select country\",\n
    }>\n {\n this.setState({alertVisible: false});\n selectedCallback(c, d);\n }} />\n ,\n null, null, _ => {}, \"Cancel\");\n }\n\n handleStartVideoCall() {\n this.setState({\n callTopic: this.state.topicSelected,\n callState: CALL_STATE_OUTGOING_INITATED,\n callAudioOnly: false\n });\n }\n\n handleStartAudioCall() {\n this.setState({\n callTopic: this.state.topicSelected,\n callState: CALL_STATE_OUTGOING_INITATED,\n callAudioOnly: true\n });\n }\n\n handleCallInvite(callTopic, callSeq, callState, audioOnly) {\n switch (callState) {\n case CALL_STATE_OUTGOING_INITATED:\n const head = { webrtc: CALL_HEAD_STARTED, aonly: !!audioOnly };\n this.handleSendMessage(Drafty.videoCall(audioOnly), undefined, undefined, head)\n .then(ctrl => {\n if (ctrl.code < 200 || ctrl.code >= 300 || !ctrl.params || !ctrl.params.seq) {\n this.handleCallClose();\n return;\n }\n this.setState({callSeq: ctrl.params['seq']});\n });\n break;\n case CALL_STATE_IN_PROGRESS:\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n // We've accepted the call. Let the other side know.\n topic.videoCall('accept', callSeq);\n break;\n }\n }\n\n handleCallRinging(callTopic, callSeq) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('ringing', callSeq);\n }\n\n handleCallHangup(callTopic, callSeq) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('hang-up', callSeq);\n }\n\n handleCallSendOffer(callTopic, callSeq, sdp) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('offer', callSeq, sdp);\n }\n\n handleCallIceCandidate(callTopic, callSeq, candidate) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('ice-candidate', callSeq, candidate);\n }\n handleCallSendAnswer(callTopic, callSeq, sdp) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('answer', callSeq, sdp);\n }\n\n handleCallClose() {\n if (this.callTimeoutTimer) {\n clearTimeout(this.callTimeoutTimer);\n }\n this.setState({\n callTopic: undefined,\n callState: CALL_STATE_NONE,\n callAudioOnly: undefined\n });\n }\n\n handleCallAccept(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n if (topic.isSubscribed()) {\n this.handleTopicSelected(this.state.callTopic);\n this.setState({\n callState: CALL_STATE_IN_PROGRESS\n });\n } else {\n // We need to switch and subscribe to callTopic first.\n this.setState({\n callShouldStart: true,\n }, _ => this.handleTopicSelected(this.state.callTopic));\n }\n }\n\n handleInfoMessage(info) {\n if (info.what != 'call') {\n return;\n }\n switch (info.event) {\n case 'accept':\n // If another my session has accepted the call.\n if (Tinode.isMeTopicName(info.topic) && this.tinode.isMe(info.from)) {\n this.setState({\n callTopic: null,\n callState: CALL_STATE_NONE,\n callSeq: null,\n callAudioOnly: undefined\n });\n return;\n }\n if (info.topic == this.state.callTopic) {\n // Update state.\n this.setState({callState: CALL_STATE_IN_PROGRESS});\n }\n break;\n case 'hang-up':\n // Remote hangup.\n this.handleCallClose();\n break;\n }\n }\n\n handleDataMessage(data) {\n if (data.head && data.head.webrtc && data.head.webrtc == CALL_HEAD_STARTED) {\n // If it's a video call invite message.\n // See if we need to display incoming call UI.\n const topic = this.tinode.getTopic(data.topic);\n if (topic) {\n // Check if a later version of the message exists (which means the call\n // has been either accepted or finished already).\n const msg = topic.latestMsgVersion(data.seq) || data;\n if (msg.head && msg.head.webrtc && msg.head.webrtc == CALL_HEAD_STARTED) {\n // This is a legit new call.\n if (data.from != this.state.myUserId) {\n if (this.state.callState == CALL_STATE_NONE) {\n // Incoming call.\n this.setState({\n callTopic: data.topic,\n callState: CALL_STATE_INCOMING_RECEIVED,\n callSeq: data.seq,\n callAudioOnly: !!msg.head.aonly\n });\n } else {\n // Another call is either in progress or being established.\n // Reject the incoming call.\n this.handleCallHangup(data.topic, data.seq);\n }\n }\n }\n } else {\n console.warn(\"Received vc data message from unknown topic\", data.topic);\n }\n }\n }\n\n render() {\n return (\n
    \n {this.state.contextMenuVisible ?\n {\n if (topicName == this.state.topicSelected) {\n this.handleTopicSelected(null);\n }\n }}\n onError={this.handleError} />\n :\n null\n }\n {this.state.forwardDialogVisible ?\n \n :\n null\n }\n {this.state.callTopic && this.state.callState == CALL_STATE_INCOMING_RECEIVED ?\n \n :\n null\n }\n {this.state.alertVisible ?\n this.setState({alertVisible: false})) : null}\n reject={this.state.alertParams.reject}\n onConfirm={this.state.alertParams.onConfirm ?\n (_ => {this.setState({alertVisible: false}); this.state.alertParams.onConfirm();}) : null}\n confirm={this.state.alertParams.confirm}\n /> : null}\n\n {!this.state.displayMobile || this.state.mobilePanel == 'sidepanel' ?\n \n : null}\n\n {!this.state.displayMobile || (this.state.mobilePanel == 'topic-view' && !this.state.infoPanel) ?\n \n : null}\n\n {this.state.infoPanel ?\n \n :\n null\n }\n
    \n );\n }\n};\n\nexport default injectIntl(TinodeWeb);\n","// View for editing topic parameters (including 'me' topic).\n\nimport React from 'react';\n\nimport TopicDescEdit from '../widgets/topic-desc-edit.jsx';\n\nimport { arrayEqual } from '../lib/utils.js';\n\nexport default class TopicCommonView extends React.Component {\n constructor(props) {\n super(props);\n\n const topic = this.props.tinode.getTopic(this.props.topic);\n const acs = topic.getAccessMode();\n this.state = {\n tags: []\n };\n\n this.previousTagsUpdated = undefined;\n\n this.onTagsUpdated = this.onTagsUpdated.bind(this);\n this.handleTagsUpdated = this.handleTagsUpdated.bind(this);\n }\n\n // No need to separately handle component mount.\n componentDidUpdate(props) {\n const topic = this.props.tinode.getTopic(props.topic);\n if (!topic) {\n return;\n }\n\n if (topic.onTagsUpdated != this.onTagsUpdated) {\n if (topic.getType() == 'grp') {\n this.previousTagsUpdated = topic.onTagsUpdated;\n topic.onTagsUpdated = this.onTagsUpdated;\n } else {\n this.previousTagsUpdated = undefined;\n }\n }\n\n if (this.state.topic != props.topic) {\n this.setState({topic: props.topic});\n }\n }\n\n componentWillUnmount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n topic.onTagsUpdated = this.previousTagsUpdated;\n }\n\n // Server informs that the tags have been updated.\n onTagsUpdated(tags) {\n this.setState({tags: tags});\n\n if (this.previousTagsUpdated && this.previousTagsUpdated != this.onTagsUpdated) {\n this.previousTagsUpdated(tags);\n }\n }\n\n // Request server to change tags.\n handleTagsUpdated(tags) {\n if (!arrayEqual(this.state.tags.slice(0), tags.slice(0))) {\n this.props.onUpdateTagsRequest(this.props.topic, tags);\n }\n }\n\n render() {\n return (\n
    \n \n
    \n );\n }\n};\n","// ValidationView: panel for confirming credentials, like email or phone.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nconst messages = defineMessages({\n phone: {\n id: 'phone_dative',\n defaultMessage: 'phone',\n description: \"Dative case of 'phone', i.e. 'phone' in 'by phone'\",\n },\n email: {\n id: 'email_dative',\n defaultMessage: 'email',\n description: \"Dative case of 'email', i.e. 'email' in 'by email'\",\n }\n});\n\nclass ValidationView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n code: props.credCode || '',\n codeReceived: props.credCode\n };\n\n this.handleCodeChange = this.handleCodeChange.bind(this);\n this.handleKeyPress = this.handleKeyPress.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n if (nextProps.credCode != prevState.codeReceived) {\n return {\n code: nextProps.credCode || '',\n codeReceived: nextProps.credCode\n };\n }\n\n return prevState;\n }\n\n componentDidMount() {\n // Submit code automatically if it's received from the parent.\n if (this.props.credCode) {\n this.props.onSubmit(this.props.credMethod, this.props.credCode, this.props.credToken);\n }\n }\n\n componentDidUpdate(prevProps, prevState) {\n // Submit code automatically if it's received from the parent.\n if (this.state.codeReceived && this.state.code && this.state.code != prevState.code) {\n this.props.onSubmit(this.props.credMethod, this.state.code, this.props.credToken);\n }\n }\n\n\n handleCodeChange(e) {\n this.setState({code: e.target.value.replace(/[^\\d]/g, '')});\n }\n\n handleKeyPress(e) {\n if (e.key === 'Enter') {\n this.handleSubmit(e);\n } else if (e.key == 'Escape') {\n this.handleCancel(e);\n }\n }\n\n handleSubmit(e) {\n e.preventDefault();\n if (this.state.code && this.state.code.trim()) {\n this.props.onSubmit(this.props.credMethod, this.state.code.trim(), this.props.credToken);\n }\n }\n\n handleCancel(e) {\n e.preventDefault();\n this.props.onCancel();\n }\n\n render() {\n const { formatMessage } = this.props.intl;\n const methods = {'email': formatMessage(messages.email), 'tel': formatMessage(messages.phone)};\n const method = methods[this.props.credMethod] || this.props.credMethod;\n return (\n
    \n
    \n \n
    \n
    \n {\n (numbers_only) => \n }\n
    \n
    \n \n \n
    \n
    \n );\n }\n};\n\nexport default injectIntl(ValidationView);\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class Alert extends React.PureComponent {\n render() {\n return (
    \n
    \n
    {this.props.title}
    \n
    {this.props.content}
    \n
    \n {this.props.onReject ?\n \n :\n null\n }\n {this.props.onConfirm ?\n \n :\n null\n }\n
    \n
    \n
    );\n }\n};\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport FileProgress from './file-progress.jsx';\nimport { bytesToHumanSize } from '../lib/strformat.js';\nimport { isUrlRelative, sanitizeUrl } from '../lib/utils.js';\n\nexport default class Attachment extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n downloader: null,\n progress: 0\n };\n\n this.downloadFile = this.downloadFile.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n downloadFile(url, filename, mimetype) {\n if (!url) {\n this.props.onError(\"Invalid download URL '\" + url + \"'\");\n return;\n }\n\n const downloader = this.props.tinode.getLargeFileHelper();\n this.setState({downloader: downloader});\n downloader.download(url, filename, mimetype,\n loaded => this.setState({progress: loaded / this.props.size}),\n err => this.props.onError(err, 'err')\n )\n .then(_ => this.setState({downloader: null, progress: 0}))\n .catch(err => {\n if (err) {\n this.props.onError(\"Error downloading file: \" + err.message, 'err');\n }\n this.setState({downloader: null, progress: 0});\n });\n }\n\n handleCancel() {\n if (this.props.uploading) {\n this.props.onCancelUpload();\n } else if (this.state.downloader) {\n this.state.downloader.cancel();\n }\n }\n\n render() {\n let filename = this.props.filename || 'file_attachment';\n if (filename.length > 36) {\n filename = filename.substr(0, 16) + '...' + filename.substr(-16);\n }\n let size = this.props.size > 0 ?\n ({bytesToHumanSize(this.props.size)}) :\n null;\n\n // Detect if the download URL is relative or absolute.\n // If the URL is relative use LargeFileHelper to attach authentication\n // credentials to the request.\n let url, helperFunc;\n if (!this.props.uploading && !this.state.downloader && isUrlRelative(this.props.downloadUrl)) {\n // Relative URL. Use download helper.\n url = '#';\n helperFunc = (e) => {\n e.preventDefault();\n this.downloadFile(this.props.downloadUrl, this.props.filename, this.props.mimetype);\n };\n } else {\n url = sanitizeUrl(this.props.downloadUrl);\n helperFunc = null;\n }\n const downloadWidget = <>file_download ;\n return (\n
    \n
    insert_drive_file
    \n
    \n
    {filename} {size}
    \n {this.props.uploading || this.state.downloader ?\n \n :\n
    {url ?\n {downloadWidget}\n :\n {downloadWidget}\n }
    \n }\n
    \n
    \n );\n }\n};\n","// Audio recorder widget.\n\nimport React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport { secondsToTime } from '../lib/strformat';\nimport { base64ToIntArray } from '../lib/blob-helpers';\n\n// Make canvas bigger than the element size to reduce blurring.\nconst CANVAS_UPSCALING = 2.0;\n// Thickness of a visualization bar.\nconst LINE_WIDTH = 3 * CANVAS_UPSCALING;\n// Spacing between two visualization bars.\nconst SPACING = 2 * CANVAS_UPSCALING;\n// Color of histogram bars.\nconst BAR_COLOR = '#888A';\nconst BAR_COLOR_DARK = '#666C';\nconst THUMB_COLOR = '#444E';\n// Minimum number of amplitude bars to draw.\nconst MIN_PREVIEW_LENGTH = 16;\n\nconst messages = defineMessages({\n icon_title_play: {\n id: 'icon_title_play',\n defaultMessage: 'Play recording',\n description: 'Icon tool tip for starting audio playback'\n }\n});\n\nclass AudioPlayer extends React.PureComponent {\n constructor(props) {\n super(props);\n\n let preview = base64ToIntArray(this.props.preview);\n if (!Array.isArray(preview) || preview.length < MIN_PREVIEW_LENGTH) {\n preview = null;\n }\n\n this.state = {\n canPlay: false,\n playing: false,\n currentTime: '0:00',\n duration: this.props.duration > 0 ? secondsToTime(this.props.duration / 1000) : '-:--',\n longMin: this.props.duration >= 600000,\n preview: preview\n };\n\n this.initAudio = this.initAudio.bind(this);\n this.initCanvas = this.initCanvas.bind(this);\n this.resampleBars = this.resampleBars.bind(this);\n this.visualize = this.visualize.bind(this);\n\n this.handlePlay = this.handlePlay.bind(this);\n this.handleSeek = this.handleSeek.bind(this);\n this.handleError = this.handleError.bind(this);\n\n this.audioPlayer = null;\n\n this.viewBuffer = [];\n this.canvasRef = React.createRef();\n }\n\n componentDidMount() {\n if (this.props.src) {\n this.initAudio();\n }\n\n this.initCanvas();\n }\n\n componentWillUnmount() {\n if (this.audioPlayer) {\n this.audioPlayer.oncanplay = null;\n this.audioPlayer.ontimeupdate = null;\n this.audioPlayer.onended = null;\n this.audioPlayer.pause();\n this.audioPlayer = null;\n }\n }\n\n componentDidUpdate(prevProps) {\n if (this.props.src != prevProps.src) {\n this.initAudio();\n }\n\n if (this.props.preview != prevProps.preview) {\n let preview = base64ToIntArray(this.props.preview);\n if (!Array.isArray(preview) || preview.length < MIN_PREVIEW_LENGTH) {\n preview = null;\n }\n this.setState({preview: preview}, this.initCanvas);\n }\n }\n\n initAudio() {\n this.audioPlayer = new Audio(this.props.src);\n this.audioPlayer.oncanplay = _ => this.setState({canPlay: true});\n this.audioPlayer.ontimeupdate = _ => this.setState({\n currentTime: secondsToTime(this.audioPlayer.currentTime, this.state.longMin)\n });\n this.audioPlayer.onended = _ => {\n this.audioPlayer.currentTime = 0;\n this.setState({playing: false, currentTime: secondsToTime(0, this.state.longMin)})\n }\n }\n\n initCanvas() {\n // Force canvas aspect ratio to match one of the element + upscale canvas to reduce blurring.\n this.canvasRef.current.width = this.canvasRef.current.offsetWidth * CANVAS_UPSCALING;\n this.canvasRef.current.height = this.canvasRef.current.offsetHeight * CANVAS_UPSCALING;\n\n this.canvasContext = this.canvasRef.current.getContext('2d');\n this.canvasContext.lineCap = 'round';\n\n this.viewBuffer = this.resampleBars(this.state.preview);\n this.visualize();\n }\n\n // Draw amplitude of sound.\n visualize() {\n if (!this.canvasRef.current) {\n return;\n }\n\n const width = this.effectiveWidth;\n const height = this.canvasRef.current.height;\n\n this.canvasContext.lineWidth = LINE_WIDTH;\n\n const drawFrame = _ => {\n if (!this.canvasRef.current || !this.audioPlayer) {\n // The component is unmounted.\n return;\n }\n\n this.canvasContext.clearRect(0, 0, this.canvasRef.current.width, height);\n\n if (this.viewBuffer) {\n if (this.state.playing) {\n window.requestAnimationFrame(drawFrame);\n }\n\n // Current playback position.\n const thumbAt = this.props.duration ?\n Math.max(0, Math.min(this.audioPlayer.currentTime * 1000 / this.props.duration, 1)) * (width - LINE_WIDTH * 2) : -1;\n\n // Draw amplitude bars.\n this.canvasContext.beginPath();\n this.canvasContext.strokeStyle = BAR_COLOR_DARK;\n for (let i = 0; i < this.viewBuffer.length; i++) {\n let x = 1 + i * (LINE_WIDTH + SPACING) + LINE_WIDTH * 0.5;\n let y = this.viewBuffer[i] * height * 0.9;\n\n const color = x < thumbAt ? BAR_COLOR_DARK : BAR_COLOR;\n if (this.canvasContext.strokeStyle != color) {\n this.canvasContext.stroke();\n this.canvasContext.beginPath();\n this.canvasContext.strokeStyle = color;\n }\n\n this.canvasContext.moveTo(x, (height - y) * 0.5);\n this.canvasContext.lineTo(x, height * 0.5 + y * 0.5);\n }\n // Actually draw the bars on canvas.\n this.canvasContext.stroke();\n\n // Draw thumb.\n if (this.props.duration) {\n this.canvasContext.beginPath();\n this.canvasContext.arc(thumbAt + LINE_WIDTH * 2, height * 0.5, LINE_WIDTH * 2, 0, 2 * Math.PI);\n this.canvasContext.fillStyle = THUMB_COLOR;\n this.canvasContext.fill();\n }\n }\n }\n\n drawFrame();\n }\n\n // Quick and dirty downsampling of the original preview bars into a smaller (or equal) number of bars we can display here.\n resampleBars(original) {\n const dstCount = ((this.canvasRef.current.width - SPACING) / (LINE_WIDTH + SPACING)) | 0;\n // Remove extra padding on the right due to fractional bar which is not drawn.\n this.effectiveWidth = dstCount * (LINE_WIDTH + SPACING) + SPACING;\n\n if (!Array.isArray(original) || original.length == 0) {\n return Array.apply(null, Array(dstCount)).map(_ => 0.01);\n }\n\n const factor = original.length / dstCount;\n let amps = [];\n let maxAmp = -1;\n for (let i=0; i 0) {\n return amps.map(a => a / maxAmp);\n }\n return Array.apply(null, Array(dstCount)).map(_ => 0.01);\n }\n\n handlePlay(e) {\n e.preventDefault();\n if (!this.state.canPlay) {\n return;\n }\n if (this.state.playing) {\n this.audioPlayer.pause();\n this.setState({playing: false});\n } else {\n this.audioPlayer.play();\n this.setState({playing: true}, this.visualize);\n }\n }\n\n handleError(err) {\n console.error(err);\n }\n\n handleSeek(e) {\n e.preventDefault();\n if (e.target && this.props.duration) {\n const rect = e.target.getBoundingClientRect();\n const offset = (e.clientX - rect.left) / this.effectiveWidth * CANVAS_UPSCALING;\n this.audioPlayer.currentTime = this.props.duration * offset / 1000;\n this.setState({currentTime: secondsToTime(this.audioPlayer.currentTime, this.state.longMin)});\n if (!this.state.playing) {\n this.visualize();\n }\n }\n }\n\n render() {\n const playClass = 'material-icons' +\n (this.props.short ? '' : ' large') +\n (this.state.canPlay ? '' : ' disabled');\n const play = (\n {this.state.playing ? 'pause_circle' :\n (this.state.canPlay ? 'play_circle' : 'not_interested')}\n );\n return (
    {this.props.short ?\n <>\n \n {play}\n \n :\n <>\n {play}\n
    \n \n
    {this.state.currentTime}/{this.state.duration}
    \n
    \n \n }\n
    );\n }\n}\n\nexport default injectIntl(AudioPlayer);\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport Cropper from './cropper.jsx';\nimport { imageCrop } from '../lib/blob-helpers.js';\n\nexport default class AvatarCrop extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n top: 0,\n left: 0,\n width: 0,\n height: 0,\n scale: 1\n };\n\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n // Cut out in image coordinates and desired scale factor.\n handleChange(left, top, width, height, scale) {\n this.setState({\n left: left,\n top: top,\n width: width,\n height: height,\n scale: scale\n });\n }\n\n handleSubmit() {\n imageCrop(this.props.mime, this.props.avatar,\n this.state.left, this.state.top, this.state.width, this.state.height,\n this.state.scale)\n .then(img => {\n this.props.onSubmit(img.mime, img.blob, img.width, img.height);\n })\n .catch(err => {\n this.props.onError(err);\n });\n }\n\n render() {\n return (\n
    \n
    \n \n
    \n
    \n {this.props.onCancel ?\n \n : null}\n \n
    \n
    \n );\n }\n};\n","import React from 'react';\n\nimport LetterTile from './letter-tile.jsx';\nimport LoadSpinner from './load-spinner.jsx';\n\nimport { sanitizeUrlForMime } from '../lib/utils.js';\n\nimport { AVATAR_SIZE } from '../config.js';\n\nexport default class AvatarUpload extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n source: props.avatar\n };\n\n this.handleFileReceived = this.handleFileReceived.bind(this);\n }\n\n componentDidUpdate(prevProps) {\n if (this.props.avatar != prevProps.avatar) {\n this.setState({source: this.props.avatar});\n }\n }\n\n handleFileReceived(e) {\n const image = e.target.files[0];\n this.props.onImageUpdated(image.type, URL.createObjectURL(image), image.name);\n // Clear the value so the same file can be uploaded again.\n e.target.value = '';\n }\n\n render() {\n // Randomize id value in case more than one AvatarUpload is shown\n // at the same time.\n const randId = 'file-input-avatar-' + ('' + Math.random()).substring(0, 4);\n const className = 'avatar-upload' + (this.props.readOnly ? ' read-only' : '');\n return (\n
    \n {this.props.readOnly || !this.state.source ?\n null :\n {e.preventDefault(); this.props.onImageUpdated();}}>\n clear\n }\n {this.state.source ?\n :\n this.props.readOnly && this.props.uid ?\n
    \n \n
    \n :\n
    {AVATAR_SIZE}×{AVATAR_SIZE}
    }\n {this.props.readOnly ? null :\n }\n {this.props.readOnly ? null :\n }\n \n
    \n );\n }\n};\n","import React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nconst icon_mapping = {'staff': 'verified_user'};\n\nconst messages = defineMessages({\n badge_verified: {\n id: 'badge_verified',\n defaultMessage: 'Verified/official',\n description: 'Explanation of a verified account or topic badge'\n },\n badge_staff: {\n id: 'badge_staff',\n defaultMessage: 'Staff-managed',\n description: 'Explanation of a staff-managed account or topic badge'\n },\n badge_danger: {\n id: 'badge_danger',\n defaultMessage: 'Untrustworthy',\n description: 'Suspicious or untrustworthy account or topic badge'\n },\n});\n\n\n/* Trusted badges with labels: verified, staff, danger */\nclass BadgeList extends React.PureComponent {\n render() {\n const {formatMessage} = this.props.intl;\n let badges = null;\n if (this.props.trustedBadges && this.props.trustedBadges.length > 0) {\n badges = [];\n this.props.trustedBadges.forEach(b => {\n const comment = this.props.short ? null : formatMessage(messages['badge_' + b]);\n const style = 'material-icons ' + b + '-color';\n badges.push(
    {icon_mapping[b] || b} {comment}
    );\n });\n return <>{badges};\n }\n return null;\n }\n};\n\nexport default injectIntl(BadgeList);\n","// The <- button to be displayed in title bars.\nimport React from 'react';\n\nexport default class ButtonBack extends React.PureComponent {\n render() {\n return (\n {e.preventDefault(); this.props.onBack();}}>\n arrow_back\n \n );\n }\n}\n","// IncomingCall: displays Accept & Reject buttons for incoming calls.\nimport React from 'react';\n\nimport BadgeList from './badge-list.jsx';\nimport LetterTile from './letter-tile.jsx';\n\nimport { MAX_TITLE_LENGTH, MAX_PEER_TITLE_LENGTH } from '../config.js';\nimport { CALL_STATE_INCOMING_RECEIVED } from '../constants.js';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\nimport { clipStr } from '../lib/utils.js'\n\nconst RING_SOUND = new Audio('audio/call-in.m4a');\n\nexport default class CallIncoming extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n topic: null,\n fullName: undefined,\n avatar: null,\n trustedBadges: [],\n previousMetaDesc: undefined,\n };\n\n this.resetDesc = this.resetDesc.bind(this);\n this.onMetaDesc = this.onMetaDesc.bind(this);\n this.handleRejectCall = this.handleRejectCall.bind(this);\n this.handleAcceptCall = this.handleAcceptCall.bind(this);\n this.ringTimer = null;\n }\n\n componentDidMount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n\n this.resetDesc(topic);\n if (this.props.callState == CALL_STATE_INCOMING_RECEIVED) {\n // play() throws if the user did not click the app first: https://goo.gl/xX8pDD.\n RING_SOUND.play().catch(_ => {});\n this.ringTimer = setInterval(_ => {RING_SOUND.play().catch(_ => {})}, 2000);\n this.props.onRinging(this.props.topic, this.props.seq);\n }\n }\n\n // No need to separately handle component mount.\n componentDidUpdate(props) {\n const topic = this.props.tinode.getTopic(props.topic);\n if (!topic) {\n return;\n }\n\n if (this.onMetaDesc != topic.onMetaDesc) {\n this.previousMetaDesc = topic.onMetaDesc;\n topic.onMetaDesc = this.onMetaDesc;\n }\n\n if (this.state.topic != props.topic) {\n this.setState({topic: props.topic});\n this.resetDesc(topic, props);\n }\n }\n\n componentWillUnmount() {\n if (this.ringTimer != null) {\n clearInterval(this.ringTimer);\n RING_SOUND.pause();\n }\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.setState({topic: null});\n topic.onMetaDesc = this.previousMetaDesc;\n }\n\n resetDesc(topic) {\n const badges = [];\n if (topic.trusted) {\n for (const [key, val] of Object.entries(topic.trusted)) {\n if (val) {\n badges.push(key);\n }\n }\n }\n\n this.setState({\n fullName: clipStr(topic.public ? topic.public.fn : undefined, MAX_TITLE_LENGTH),\n avatar: makeImageUrl(topic.public ? topic.public.photo : null),\n trustedBadges: badges,\n });\n }\n\n onMetaDesc(desc) {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.resetDesc(topic);\n\n if (this.previousMetaDesc && this.previousMetaDesc != this.onMetaDesc) {\n this.previousMetaDesc(desc);\n }\n }\n\n handleAcceptCall() {\n this.props.onAcceptCall(this.props.topic);\n }\n\n handleRejectCall() {\n this.props.onReject(this.props.topic, this.props.seq);\n this.props.onClose();\n }\n\n render() {\n return (\n
    \n
    \n
    \n
    \n \n
    \n
    {clipStr(this.state.fullName, MAX_PEER_TITLE_LENGTH)}\n
    \n
    \n
    \n {this.props.callState == CALL_STATE_INCOMING_RECEIVED ?\n <>\n \n \n \n :\n null\n }\n
    \n
    \n
    \n );\n }\n};\n","// Chat message describing a video or voice call.\n\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { secondsToTime } from '../lib/strformat.js';\n\nexport default class CallMessage extends React.PureComponent {\n render() {\n const isCallDropped = ['busy', 'declined', 'disconnected', 'missed'].includes(this.props.callState);\n const successClass = 'material-icons medium ' + (isCallDropped ? 'red' : 'green');\n const callIcon = this.props.incoming ?\n (isCallDropped ? 'call_missed' : 'call_received') :\n (isCallDropped ? 'call_missed_outgoing' : 'call_made');\n let duration;\n if (isCallDropped) {\n switch (this.props.callState) {\n case 'busy':\n duration = ;\n break;\n case 'declined':\n duration = ;\n break;\n case 'missed':\n duration = this.props.incoming ?\n :\n ;\n break;\n default:\n duration = ;\n break;\n }\n } else {\n duration = {secondsToTime(this.props.duration / 1000)};\n }\n return
    \n
    call
    \n
    \n
    {this.props.incoming ?\n :\n \n }
    \n
    {callIcon} {duration}
    \n
    \n
    ;\n }\n}\n","// CallPanel displays call in progress: local and remote viewports and controls.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport LetterTile from './letter-tile.jsx';\n\nimport { MAX_PEER_TITLE_LENGTH } from '../config.js';\nimport { CALL_STATE_OUTGOING_INITATED, CALL_STATE_IN_PROGRESS } from '../constants.js';\n\nimport { clipStr } from '../lib/utils.js'\n\nconst RING_SOUND = new Audio('audio/call-out.m4a');\nRING_SOUND.loop = true;\nconst CALL_ENDED_SOUND = new Audio('audio/call-end.m4a');\nCALL_ENDED_SOUND.loop = true;\nconst DIALING_SOUND = new Audio('audio/dialing.m4a');\n\nconst VIDEO_MUTED_EVENT = 'video:muted';\nconst VIDEO_UNMUTED_EVENT = 'video:unmuted';\n\nconst messages = defineMessages({\n already_in_call: {\n id: 'already_in_call',\n defaultMessage: 'You already in an ongoing call!',\n description: 'Error message when the user tried to accept a new call without finishing pervious one',\n }\n});\n\nclass CallPanel extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n localStream: undefined,\n remoteStream: undefined,\n pc: undefined,\n dataChannel: undefined,\n\n previousOnInfo: undefined,\n waitingForPeer: false,\n // If true, the client has received a remote SDP from the peer and has sent a local SDP to the peer.\n callInitialSetupComplete: false,\n audioOnly: props.callAudioOnly,\n // Video mute/unmute in progress.\n videoToggleInProgress: false,\n // Indicates if the remote peer has informed us that their camera is on.\n remoteVideoLive: false,\n };\n\n this.localStreamConstraints = {\n audio: true,\n video: !props.callAudioOnly\n };\n this.isOutgoingCall = props.callState == CALL_STATE_OUTGOING_INITATED;\n\n this.localRef = React.createRef();\n this.remoteRef = React.createRef();\n // Cache for remote ice candidates until initial setup gets completed.\n this.remoteIceCandidatesCache = [];\n\n this.onInfo = this.onInfo.bind(this);\n this.start = this.start.bind(this);\n this.stop = this.stop.bind(this);\n\n this.createPeerConnection = this.createPeerConnection.bind(this);\n this.canSendOffer = this.canSendOffer.bind(this);\n this.drainRemoteIceCandidatesCache = this.drainRemoteIceCandidatesCache.bind(this);\n\n this.handleNegotiationNeededEvent = this.handleNegotiationNeededEvent.bind(this);\n this.handleICECandidateEvent = this.handleICECandidateEvent.bind(this);\n this.handleNewICECandidateMsg = this.handleNewICECandidateMsg.bind(this);\n this.handleICEConnectionStateChangeEvent = this.handleICEConnectionStateChangeEvent.bind(this);\n this.handleSignalingStateChangeEvent = this.handleSignalingStateChangeEvent.bind(this);\n this.handleICEGatheringStateChangeEvent = this.handleICEGatheringStateChangeEvent.bind(this);\n this.handleIceCandidateErrorEvent = this.handleIceCandidateErrorEvent.bind(this);\n this.handleTrackEvent = this.handleTrackEvent.bind(this);\n\n this.handleVideoOfferMsg = this.handleVideoOfferMsg.bind(this);\n this.handleVideoAnswerMsg = this.handleVideoAnswerMsg.bind(this);\n this.handleNewICECandidateMsg = this.handleNewICECandidateMsg.bind(this);\n\n this.reportError = this.reportError.bind(this);\n this.handleGetUserMediaError = this.handleGetUserMediaError.bind(this);\n\n this.stopTracks = this.stopTracks.bind(this);\n this.disconnectMedia = this.disconnectMedia.bind(this);\n\n this.handleCloseClick = this.handleCloseClick.bind(this);\n this.handleToggleCameraClick = this.handleToggleCameraClick.bind(this);\n this.handleToggleMicClick = this.handleToggleMicClick.bind(this);\n\n this.handleRemoteHangup = this.handleRemoteHangup.bind(this);\n this.handleVideoCallAccepted = this.handleVideoCallAccepted.bind(this);\n\n this.muteVideo = this.muteVideo.bind(this);\n this.unmuteVideo = this.unmuteVideo.bind(this);\n this.emptyVideoTrack = this.emptyVideoTrack.bind(this);\n\n this.handleDataChannelEvent = this.handleDataChannelEvent.bind(this);\n this.handleDataChannelError = this.handleDataChannelError.bind(this);\n this.handleDataChannelMessage = this.handleDataChannelMessage.bind(this);\n this.handleDataChannelOpen = this.handleDataChannelOpen.bind(this);\n this.handleDataChannelClose = this.handleDataChannelClose.bind(this);\n }\n\n componentDidMount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n this.previousOnInfo = topic.onInfo;\n topic.onInfo = this.onInfo;\n if ((this.props.callState == CALL_STATE_OUTGOING_INITATED ||\n this.props.callState == CALL_STATE_IN_PROGRESS) && this.localRef.current) {\n this.start();\n }\n }\n\n componentWillUnmount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n topic.onInfo = this.previousOnInfo;\n this.stop();\n }\n\n handleVideoCallAccepted(info) {\n RING_SOUND.pause();\n // Create peer connection with a data channel.\n const pc = this.createPeerConnection(true);\n const stream = this.state.localStream;\n stream.getTracks().forEach(track => {\n pc.addTrack(track, stream);\n\n if (track.kind == 'video' && this.state.audioOnly) {\n // This is an audio-only call.\n // Remove dummy video track (placeholder remains).\n track.enabled = false;\n track.stop();\n stream.removeTrack(track);\n }\n });\n }\n\n onInfo(info) {\n if (info.what != 'call') {\n return;\n }\n switch (info.event) {\n case 'accept':\n this.handleVideoCallAccepted(info);\n break;\n case 'answer':\n this.handleVideoAnswerMsg(info);\n break;\n case 'ice-candidate':\n this.handleNewICECandidateMsg(info);\n break;\n case 'hang-up':\n this.handleRemoteHangup(info);\n break;\n case 'offer':\n this.handleVideoOfferMsg(info);\n break;\n case 'ringing':\n // play() throws if the user did not click the app first: https://goo.gl/xX8pDD.\n RING_SOUND.play().catch(_ => {});\n break;\n default:\n console.warn(\"Unknown call event\", info.event);\n break;\n }\n }\n\n // Creates an empty video track placeholder.\n emptyVideoTrack() {\n const width = 640;\n const height = 480;\n const canvas = Object.assign(document.createElement(\"canvas\"), {width, height});\n canvas.getContext('2d').fillRect(0, 0, width, height);\n const stream = canvas.captureStream(0);\n return Object.assign(stream.getVideoTracks()[0], {enabled: false});\n }\n\n start() {\n if (this.state.localStream) {\n this.props.onError(this.props.intl.formatMessage(messages.already_in_call), 'info');\n return;\n }\n\n if (this.props.callState == CALL_STATE_IN_PROGRESS) {\n // We apparently just accepted the call.\n this.props.onInvite(this.props.topic, this.props.seq, CALL_STATE_IN_PROGRESS, this.props.callAudioOnly);\n return;\n }\n\n // This is an outgoing call waiting for the other side to pick up.\n // Start local video.\n navigator.mediaDevices.getUserMedia(this.localStreamConstraints)\n .then(stream => {\n if (!this.localStreamConstraints.video) {\n // Starting an audio-only call. Create a dummy video track\n // (so video can be enabled during the call if the user desires).\n stream.addTrack(this.emptyVideoTrack());\n }\n this.setState({localStream: stream, waitingForPeer: true});\n this.localRef.current.srcObject = stream;\n\n DIALING_SOUND.play();\n\n // Send call invitation.\n this.props.onInvite(this.props.topic, this.props.seq, this.props.callState, this.props.callAudioOnly);\n })\n .catch(this.handleGetUserMediaError);\n }\n\n stop() {\n CALL_ENDED_SOUND.pause();\n CALL_ENDED_SOUND.currentTime = 0;\n RING_SOUND.pause();\n RING_SOUND.currentTime = 0;\n\n this.stopTracks(this.state.localStream);\n this.stopTracks(this.state.remoteStream);\n this.disconnectMedia(this.localRef.current);\n this.disconnectMedia(this.remoteRef.current);\n if (this.state.pc) {\n this.state.pc.ontrack = null;\n this.state.pc.onremovetrack = null;\n this.state.pc.onremovestream = null;\n this.state.pc.onicecandidate = null;\n this.state.pc.oniceconnectionstatechange = null;\n this.state.pc.onsignalingstatechange = null;\n this.state.pc.onicegatheringstatechange = null;\n this.state.pc.onnegotiationneeded = null;\n this.state.pc.onicecandidateerror = null;\n this.state.pc.ondatachannel = null;\n\n if (this.state.dataChannel && (this.state.dataChannel.readyState == 'open' || this.state.dataChannel.readyState == 'connecting')) {\n this.state.dataChannel.close();\n }\n this.state.pc.close();\n }\n this.setState({pc: null, waitingForPeer: false});\n }\n\n disconnectMedia(el) {\n if (!el) {\n return;\n }\n\n el.srcObject = null;\n el.src = '';\n }\n\n stopTracks(stream) {\n if (!stream) {\n return;\n }\n\n let tracks = stream.getTracks();\n if (tracks) {\n tracks.forEach(track => {\n track.stop();\n track.enabled = false;\n });\n }\n }\n\n handleDataChannelError(error) {\n console.error('data channel error', error);\n }\n\n handleDataChannelMessage(event) {\n switch (event.data) {\n case VIDEO_MUTED_EVENT:\n this.setState({remoteVideoLive: false}, _ => { this.remoteRef.current.srcObject = this.state.remoteStream; });\n break;\n case VIDEO_UNMUTED_EVENT:\n this.setState({remoteVideoLive: true}, _ => { this.remoteRef.current.srcObject = this.state.remoteStream; });\n break;\n default:\n break;\n }\n }\n\n handleDataChannelOpen(event) {\n if (!this.state.audioOnly) {\n event.target.send(VIDEO_UNMUTED_EVENT);\n }\n }\n\n handleDataChannelClose(event) {\n console.log('close data channel:', event);\n }\n\n handleDataChannelEvent(event) {\n console.log('data channel event:', event);\n const channel = event.channel;\n channel.onerror = this.handleDataChannelError;\n channel.onmessage = this.handleDataChannelMessage;\n channel.onopen = this.handleDataChannelOpen;\n channel.onclose = this.handleDataChannelClose;\n this.setState({dataChannel: channel});\n }\n\n createPeerConnection(withDataChannel) {\n const iceServers = this.props.tinode.getServerParam('iceServers', null);\n const pc = iceServers ? new RTCPeerConnection({iceServers: iceServers}) : new RTCPeerConnection();\n\n pc.onicecandidate = this.handleICECandidateEvent;\n pc.oniceconnectionstatechange = this.handleICEConnectionStateChangeEvent;\n pc.onicegatheringstatechange = this.handleICEGatheringStateChangeEvent;\n pc.onsignalingstatechange = this.handleSignalingStateChangeEvent;\n pc.onnegotiationneeded = this.handleNegotiationNeededEvent;\n pc.onicecandidateerror = this.handleIceCandidateErrorEvent;\n pc.ontrack = this.handleTrackEvent;\n pc.ondatachannel = this.handleDataChannelEvent;\n\n let stateUpdate = {pc: pc, waitingForPeer: false};\n if (withDataChannel) {\n // Create data channel for exchanging events.\n const channel = pc.createDataChannel(\"events\", {ordered: true});\n channel.onerror = this.handleDataChannelError;\n channel.onmessage = this.handleDataChannelMessage;\n channel.onopen = this.handleDataChannelOpen;\n channel.onclose = this.handleDataChannelClose;\n stateUpdate.dataChannel = channel;\n }\n this.setState(stateUpdate);\n return pc;\n }\n\n handleVideoAnswerMsg(info) {\n // Configure the remote description, which is the SDP payload\n // in 'info' message.\n const desc = new RTCSessionDescription(info.payload);\n this.state.pc.setRemoteDescription(desc)\n .then(_ => {\n this.setState({ callInitialSetupComplete: true }, _ => this.drainRemoteIceCandidatesCache());\n })\n .catch(err => this.reportError(err));\n }\n\n reportError(err) {\n this.props.onError(err.message, 'err');\n }\n\n canSendOffer() {\n return this.isOutgoingCall || this.state.callInitialSetupComplete;\n }\n\n handleNegotiationNeededEvent(event) {\n const pc = event.target;\n if (!this.canSendOffer()) {\n return;\n }\n pc.createOffer().then(offer => {\n return pc.setLocalDescription(offer);\n })\n .then(_ => {\n this.props.onSendOffer(this.props.topic, this.props.seq, pc.localDescription.toJSON());\n })\n .catch(err => this.reportError(err));\n }\n\n handleIceCandidateErrorEvent(event) {\n console.warn(\"ICE candidate error:\", event);\n }\n\n handleICECandidateEvent(event) {\n if (event.candidate) {\n this.props.onIceCandidate(this.props.topic, this.props.seq, event.candidate.toJSON());\n }\n }\n\n handleNewICECandidateMsg(info) {\n const candidate = new RTCIceCandidate(info.payload);\n if (this.state.callInitialSetupComplete) {\n this.state.pc.addIceCandidate(candidate)\n .catch(err => {\n if (candidate.candidate) {\n this.reportError(err);\n }\n console.warn(\"Error adding new ice candidate\", candidate, err);\n });\n } else {\n this.remoteIceCandidatesCache.push(candidate);\n }\n }\n\n drainRemoteIceCandidatesCache() {\n this.remoteIceCandidatesCache.forEach(candidate => {\n this.state.pc.addIceCandidate(candidate)\n .catch(err => {\n if (candidate.candidate) {\n this.reportError(err);\n }\n console.warn(\"Error adding cached ice candidate\", candidate, err);\n });\n });\n this.remoteIceCandidatesCache = [];\n }\n\n handleICEConnectionStateChangeEvent(event) {\n switch (event.target.iceConnectionState) {\n case 'closed':\n case 'failed':\n this.handleCloseClick();\n break;\n }\n }\n\n handleSignalingStateChangeEvent(event) {\n if (event.target.signalingState == 'closed') {\n this.handleCloseClick();\n }\n }\n\n handleICEGatheringStateChangeEvent(event) {\n // ICE gathering change state\n }\n\n handleTrackEvent(event) {\n // Remote video becomes available.\n this.remoteRef.current.srcObject = event.streams[0];\n this.setState({remoteStream: event.streams[0]});\n }\n\n handleGetUserMediaError(e) {\n console.error(\"Error opening camera and/or microphone\", e);\n switch(e.name) {\n case 'NotFoundError':\n // Cannot start the call b/c no camera and/or microphone found.\n this.reportError(e);\n break;\n case 'SecurityError':\n case 'PermissionDeniedError':\n // Do nothing; this is the same as the user canceling the call.\n break;\n default:\n this.reportError(e);\n break;\n }\n\n // Make sure we shut down our end of the RTCPeerConnection so we're\n // ready to try again.\n this.handleCloseClick();\n }\n\n handleVideoOfferMsg(info) {\n let localStream = null;\n // If needed, create peer connection.\n // Not creating data channel since it should be created by the peer.\n const pc = this.state.pc ? this.state.pc : this.createPeerConnection(false);\n const desc = new RTCSessionDescription(info.payload);\n\n pc.setRemoteDescription(desc).then(_ => {\n return navigator.mediaDevices.getUserMedia(this.localStreamConstraints);\n })\n .then(stream => {\n let dummyVideo;\n if (!this.localStreamConstraints.video) {\n // Starting an audio-only call. Create an empty video track so\n // so the user can enable the video during the call.\n dummyVideo = this.emptyVideoTrack();\n stream.addTrack(dummyVideo);\n }\n localStream = stream;\n this.localRef.current.srcObject = stream;\n this.setState({localStream: stream});\n\n localStream.getTracks().forEach(track => {\n pc.addTrack(track, localStream);\n });\n\n if (dummyVideo) {\n dummyVideo.enabled = false;\n dummyVideo.stop();\n stream.removeTrack(dummyVideo);\n }\n })\n .then(_ => {\n return pc.createAnswer();\n })\n .then(answer => {\n return pc.setLocalDescription(answer);\n })\n .then(_ => {\n this.props.onSendAnswer(this.props.topic, this.props.seq, pc.localDescription.toJSON());\n this.setState({ callInitialSetupComplete: true }, _ => this.drainRemoteIceCandidatesCache());\n })\n .catch(this.handleGetUserMediaError);\n }\n\n // Call disconnected by remote.\n handleRemoteHangup() {\n if (!this.state.waitingForPeer) {\n // This is live call, just hang up.\n this.handleCloseClick();\n } else {\n // This is a call which is not yet connected.\n // Stop pulse animation.\n this.setState({waitingForPeer: false});\n // Change sound and wait a bit before ending it.\n RING_SOUND.pause();\n RING_SOUND.currentTime = 0;\n CALL_ENDED_SOUND.loop = true;\n CALL_ENDED_SOUND.play().catch(_ => {});\n setTimeout(_ => {\n this.handleCloseClick();\n }, 2000);\n }\n }\n\n handleCloseClick() {\n this.stop();\n this.props.onHangup(this.props.topic, this.props.seq);\n }\n\n // Ends video track and turns off the camera.\n muteVideo() {\n if (!this.state.pc || !this.state.dataChannel) {\n return;\n }\n\n const stream = this.state.localStream;\n const t = stream.getVideoTracks()[0];\n t.enabled = false;\n t.stop();\n\n stream.removeTrack(t);\n this.state.dataChannel.send(VIDEO_MUTED_EVENT);\n this.setState({videoToggleInProgress: false});\n }\n\n unmuteVideo() {\n if (!this.state.pc || !this.state.dataChannel) {\n return;\n }\n navigator.mediaDevices.getUserMedia({ video: true })\n .then(stream => {\n // Will extract video track from stream and throw stream away,\n // and replace video track in the media sender.\n this.localRef.current.srcObject = null;\n const sender = this.state.pc.getSenders().find(s => s.track.kind == 'video');\n const track = stream.getVideoTracks()[0];\n // Remote track from new stream.\n stream.removeTrack(track);\n // Add this track to the existing local stream.\n this.state.localStream.addTrack(track);\n return sender.replaceTrack(track);\n })\n .then(_ => {\n this.localRef.current.srcObject = this.state.localStream;\n this.state.dataChannel.send(VIDEO_UNMUTED_EVENT);\n })\n .catch(err => this.handleGetUserMediaError(err))\n .finally(_ => { this.setState({videoToggleInProgress: false}); }); // Make sure we redraw the mute/unmute icons (e.g. camera -> camera_off).\n }\n\n handleToggleCameraClick() {\n if (this.state.videoToggleInProgress) {\n // Toggle currently in progress.\n return;\n }\n const tracks = this.state.localStream.getVideoTracks();\n this.setState({videoToggleInProgress: true}, _ => {\n if (tracks && tracks.length > 0 && tracks[0].enabled && tracks[0].readyState == 'live') {\n this.muteVideo();\n } else {\n this.unmuteVideo();\n }\n this.setState({audioOnly: !this.state.audioOnly});\n });\n }\n\n handleToggleMicClick() {\n const stream = this.state.localStream;\n const t = stream.getAudioTracks()[0];\n t.enabled = !t.enabled;\n // Make sure we redraw the mute/unmute icons (e.g. mic -> mic_off).\n this.forceUpdate();\n }\n\n render() {\n const audioTracks = this.state.localStream && this.state.localStream.getAudioTracks();\n const videoTracks = !this.state.audioOnly && this.state.localStream && this.state.localStream.getVideoTracks();\n const disabled = !this.state.pc || !this.state.dataChannel || !(audioTracks && audioTracks[0]);\n const audioIcon = audioTracks && audioTracks[0] && audioTracks[0].enabled ? 'mic' : 'mic_off';\n const videoIcon = videoTracks && videoTracks[0] && videoTracks[0].enabled && videoTracks[0].readyState == 'live' ? 'videocam' : 'videocam_off';\n const peerTitle = clipStr(this.props.title, MAX_PEER_TITLE_LENGTH);\n const pulseAnimation = this.state.waitingForPeer ? ' pulse' : '';\n\n let remoteActive = false;\n if (this.remoteRef.current && this.remoteRef.current.srcObject && this.state.remoteVideoLive) {\n const rstream = this.remoteRef.current.srcObject;\n if (rstream.getVideoTracks().length > 0) {\n const t = rstream.getVideoTracks()[0];\n remoteActive = t.enabled && t.readyState == 'live';\n }\n }\n\n return (\n <>\n
    \n
    \n
    \n
    \n
    \n {remoteActive ?\n <>\n
    \n
    \n
    \n \n \n \n
    \n
    \n \n );\n }\n};\n\nexport default injectIntl(CallPanel);\n","// The counter of unread messages in the topic.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { secondsToTime } from '../lib/strformat.js';\n\n// Props:\n// incoming: true | false.\n// success: true | false.\nexport default class CallStatus extends React.PureComponent {\n render() {\n const isCallDropped = ['busy', 'declined', 'disconnected', 'missed'].includes(this.props.callState);\n const icon2 = this.props.incoming ?\n (isCallDropped ? 'call_missed' : 'call_received') :\n (isCallDropped ? 'call_missed_outgoing' : 'call_made');\n let duration;\n if (isCallDropped) {\n switch (this.props.callState) {\n case 'busy':\n duration = ;\n break;\n case 'declined':\n duration = ;\n break;\n case 'missed':\n duration = this.props.incoming ?\n :\n ;\n break;\n default:\n duration = ;\n break;\n }\n } else if (['accepted', 'started'].includes(this.props.callState) && !this.props.duration) {\n duration = \n } else {\n duration = {secondsToTime(this.props.duration / 1000)};\n }\n return (\n <>\n
    \n call{icon2}\n
    {duration}\n \n );\n }\n};\n","// Single chat message bubble, sent or received.\n\nimport React from 'react';\nimport { FormattedMessage, injectIntl } from 'react-intl';\nimport { Drafty, Tinode } from 'tinode-sdk';\n\nimport Attachment from './attachment.jsx';\nimport LetterTile from './letter-tile.jsx';\nimport ReceivedMarker from './received-marker.jsx'\n\nimport { fullFormatter } from '../lib/formatters.js';\nimport { sanitizeUrl } from '../lib/utils.js';\n\nclass BaseChatMessage extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n progress: 0\n };\n\n if (props.uploader) {\n props.uploader.onProgress = this.handleProgress.bind(this);\n }\n\n this.handleExpandImage = this.handleExpandImage.bind(this);\n this.handlePlayVideo = this.handlePlayVideo.bind(this);\n this.handleFormButtonClick = this.handleFormButtonClick.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n this.handleCancelUpload = this.handleCancelUpload.bind(this);\n this.handleQuoteClick = this.handleQuoteClick.bind(this);\n\n this.formatterContext = {\n formatMessage: props.intl.formatMessage.bind(props.intl),\n viewportWidth: props.viewportWidth,\n authorizeURL: props.tinode.authorizeURL.bind(props.tinode),\n\n onImagePreview: this.handleExpandImage,\n onVideoPreview: this.handlePlayVideo,\n onFormButtonClick: this.handleFormButtonClick,\n onQuoteClick: this.handleQuoteClick\n };\n }\n\n handleExpandImage(e) {\n e.preventDefault();\n this.props.onExpandMedia({\n url: e.target.src,\n filename: e.target.dataset.name,\n width: e.target.dataset.width,\n height: e.target.dataset.height,\n size: e.target.dataset.size,\n type: e.target.dataset.mime\n });\n }\n\n handlePlayVideo(e) {\n e.preventDefault();\n this.props.onExpandMedia({\n video: true,\n url: e.target.dataset.src,\n preview: e.target.src,\n filename: e.target.dataset.name,\n width: e.target.dataset.width,\n height: e.target.dataset.height,\n duration: e.target.dataset.duration,\n size: e.target.dataset.size,\n type: e.target.dataset.mime\n });\n }\n\n handleFormButtonClick(e) {\n e.preventDefault();\n const data = {\n seq: this.props.seq\n };\n data.resp = {};\n if (e.target.dataset.name) {\n data.resp[e.target.dataset.name] = e.target.dataset.val ? e.target.dataset.val :\n e.target.dataset.val === undefined ? 1 : '' + e.target.dataset.val;\n }\n if (e.target.dataset.act == 'url') {\n data.ref = sanitizeUrl(e.target.dataset.ref) || 'about:blank';\n }\n const text = e.target.dataset.title || 'unknown';\n this.props.onFormResponse(e.target.dataset.act, text, data);\n }\n\n handleContextClick(e) {\n e.preventDefault();\n e.stopPropagation();\n const menuItems = [];\n if (this.props.received == Tinode.MESSAGE_STATUS_FAILED) {\n menuItems.push('menu_item_send_retry');\n }\n if (this.props.received > Tinode.MESSAGE_STATUS_FATAL) {\n if (this.props.userIsWriter) {\n menuItems.push('menu_item_reply');\n if (!this.props.response) {\n let immutable = false;\n Drafty.entities(this.props.content, (_0, _1, tp) => {\n immutable = ['AU', 'EX', 'FM', 'IM', 'VC', 'VD'].includes(tp);\n return immutable;\n });\n if (!immutable) {\n Drafty.styles(this.props.content, tp => {\n immutable = ['QQ'].includes(tp);\n return immutable;\n });\n }\n if (!immutable) {\n menuItems.push('menu_item_edit');\n }\n }\n }\n if (this.props.userIsAdmin) {\n menuItems.push(this.props.pinned ? 'menu_item_unpin' : 'menu_item_pin');\n }\n }\n menuItems.push('menu_item_forward');\n\n this.props.showContextMenu({\n seq: this.props.seq,\n replace: this.props.edited ? parseInt(this.props.edited.split(':')[1]) : 0,\n content: this.props.content,\n userFrom: this.props.userFrom,\n userName: this.props.userName,\n y: e.pageY,\n x: e.pageX,\n pickReply: this.props.pickReply,\n editMessage: this.props.editMessage,\n }, menuItems);\n }\n\n handleProgress(ratio) {\n this.setState({progress: ratio});\n }\n\n handleCancelUpload() {\n this.props.onCancelUpload(this.props.seq, this.props.uploader);\n }\n\n handleQuoteClick(e) {\n e.preventDefault();\n e.stopPropagation();\n const replyToSeq = this.props.replyToSeq;\n if (replyToSeq) {\n this.props.onQuoteClick(replyToSeq);\n }\n }\n\n render() {\n const sideClass = this.props.sequence + ' ' + (this.props.response ? 'left' : 'right');\n const bubbleClass = (this.props.sequence == 'single' || this.props.sequence == 'last') ? 'bubble tip' : 'bubble';\n const avatar = this.props.userAvatar || true;\n const fullDisplay = (this.props.isGroup && this.props.response &&\n (this.props.sequence == 'single' || this.props.sequence == 'last'));\n\n let content = this.props.content;\n const attachments = [];\n if (this.props.mimeType == Drafty.getContentType() && Drafty.isValid(content)) {\n Drafty.attachments(content, (att, i) => {\n if (att.mime == 'application/json') {\n // Don't show json objects as attachments.\n // They are not meant for users.\n return;\n }\n attachments.push();\n }, this);\n const tree = Drafty.format(content, fullFormatter, this.formatterContext);\n content = React.createElement(React.Fragment, null, tree);\n } else if (typeof content != 'string') {\n content = <>warning_amber \n \n }\n\n return (\n
  • \n {this.props.isGroup && this.props.response ?\n
    \n {fullDisplay ?\n :\n null}\n
    :\n null}\n
    \n
    \n
    \n
    \n {content}\n {attachments}\n
    \n {this.props.timestamp ?\n \n : null}\n
    \n {this.props.showContextMenu ?\n \n \n expand_more\n \n : null\n }\n
    \n {fullDisplay ?\n
    \n {this.props.userName ||\n \n }\n
    \n : null\n }\n
    \n
  • \n );\n }\n};\n\nconst IntlChatMessage = injectIntl(BaseChatMessage);\nconst ChatMessage = React.forwardRef((props, ref) => );\n\nexport default ChatMessage;\n","import React from 'react';\n\n/* CheckBox: styled three-state checkbox, either clickable or static */\nexport default class CheckBox extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n handleChange() {\n this.props.onChange(this.props.name, !this.props.checked);\n }\n\n render() {\n let classList = ['material-icons'];\n let iconName;\n if (Array.isArray(this.props.className)) {\n classList.push(...this.props.className);\n } else if (this.props.className) {\n classList.push(this.props.className);\n }\n if (this.props.onChange) {\n if (this.props.checked) {\n classList.push('blue', 'clickable');\n iconName = 'check_box';\n } else if (this.props.checked === false) {\n classList.push('blue', 'clickable');\n iconName = 'check_box_outline_blank';\n } else {\n classList.push('lt-blue');\n iconName = 'indeterminate_check_box';\n }\n } else {\n if (this.props.checked) {\n iconName = 'check_box';\n } else {\n iconName = 'check_box_outline_blank';\n }\n }\n let attrs = {\n className: classList.join(' '),\n id: this.props.id,\n };\n if (this.props.onChange) {\n attrs.onClick = this.handleChange;\n }\n return React.createElement('i', attrs, iconName);\n }\n}\n","import React from 'react';\n\nimport Chip from './chip.jsx';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\n/* BEGIN ChipInput: group membership widget */\nexport default class ChipInput extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = ChipInput.deriveStateFromProps(props);\n this.state.input = '';\n this.state.focused = false;\n\n this.handleTextInput = this.handleTextInput.bind(this);\n this.removeChipAt = this.removeChipAt.bind(this);\n this.handleChipCancel = this.handleChipCancel.bind(this);\n this.handleFocusGained = this.handleFocusGained.bind(this);\n this.handleFocusLost = this.handleFocusLost.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n }\n\n static deriveStateFromProps(props) {\n return {\n placeholder: props.chips ? '' : props.prompt,\n sortedChips: ChipInput.sortChips(props.chips, props.staticMembers),\n chipIndex: ChipInput.indexChips(props.chips)\n };\n }\n\n componentDidUpdate(prevProps, prevState) {\n if (prevProps.chips != this.props.chips ||\n prevProps.staticMembers != this.props.staticMembers ||\n prevProps.prompt != this.props.prompt) {\n this.setState(ChipInput.deriveStateFromProps(this.props));\n }\n if (!prevState || this.props.chips.length > prevState.sortedChips.length) {\n this.setState({input: ''});\n }\n }\n\n // Map chip index to user name\n static indexChips(chips) {\n const index = {};\n let count = 0;\n chips.forEach(item => {\n index[item.user] = count;\n count ++;\n });\n return index;\n }\n\n // Have non-removable chips appear before all other chips.\n static sortChips(chips, keep) {\n const required = [];\n const normal = [];\n chips.forEach(item => {\n if (keep && keep.includes(item.user)) {\n required.push(item);\n } else {\n normal.push(item);\n }\n });\n return required.concat(normal);\n }\n\n handleTextInput(e) {\n this.setState({input: e.target.value});\n if (this.props.filterFunc) {\n this.props.filterFunc(e.target.value);\n }\n }\n\n removeChipAt(idx) {\n const removed = this.state.sortedChips[idx];\n this.props.onChipRemoved(removed.user, this.state.chipIndex[removed.user]);\n }\n\n handleChipCancel(item, idx) {\n this.removeChipAt(idx);\n }\n\n handleFocusGained() {\n this.setState({focused: true});\n }\n\n handleFocusLost() {\n this.setState({focused: false});\n if (this.props.onFocusLost) {\n this.props.onFocusLost(this.state.input);\n }\n }\n\n handleKeyDown(e) {\n if (e.key === 'Backspace') {\n if (this.state.input.length == 0 && this.state.sortedChips.length > 0) {\n const at = this.state.sortedChips.length - 1;\n if (this.state.sortedChips[at].user !== this.props.staticMembers) {\n this.removeChipAt(at);\n }\n }\n } else if (e.key === 'Enter') {\n if (this.props.onEnter) {\n this.props.onEnter(this.state.input);\n }\n } else if (e.key === 'Escape') {\n if (this.props.onCancel) {\n this.props.onCancel();\n }\n }\n }\n\n render() {\n const chips = [];\n let count = 0;\n const staticMembers = this.props.staticMembers || [];\n this.state.sortedChips.forEach(item => {\n chips.push(\n \n );\n count++;\n });\n const className = \"chip-input\" + (this.state.focused ? ' focused' : '');\n const autoFocus = !(this.props.tabIndex > 0);\n return (\n
    \n {chips}\n \n
    \n );\n }\n};\n","import React from 'react';\n\nimport LetterTile from './letter-tile.jsx';\n\nexport default class Chip extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n handleCancel(e) {\n e.preventDefault();\n this.props.onCancel(this.props.topic, this.props.index);\n }\n\n render() {\n const title = this.props.title || this.props.topic;\n const className = this.props.invalid ? 'chip invalid' : 'chip';\n return (\n
    \n {this.props.noAvatar ?\n :\n
    \n \n
    \n }\n {title}\n {this.props.onCancel && !this.props.required ?\n ×\n : }\n
    \n );\n }\n};\n","// A panel included into a list of contacts with an action text.\nimport React from 'react';\nimport { injectIntl } from 'react-intl';\n\nclass ContactAction extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleClick = this.handleClick.bind(this);\n }\n\n handleClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.onAction(this.props.action);\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n return (\n
  • \n
    {formatMessage(this.props.title, this.props.values)}
    \n
  • \n );\n }\n};\n\nexport default injectIntl(ContactAction);\n","import React from 'react';\n\nconst icon_mapping = {'muted': 'notifications_off', 'banned': 'block', 'staff': 'verified_user'};\n\n/* Contact's labels: [you], or icons [muted], [blocked] */\nexport default class ContactBadges extends React.PureComponent {\n render() {\n let badges = null;\n if (this.props.badges && this.props.badges.length > 0) {\n badges = [];\n this.props.badges.forEach(b => {\n const color = (b.color ? ' ' + b.color : '');\n if (b.icon) {\n badges.push({icon_mapping[b.icon] || b.icon});\n } else {\n badges.push({b.name});\n }\n });\n return <>{badges};\n }\n return null;\n }\n};\n","// ContactList: component for showing a list of contacts,\n// such as a list of group members in a group chat.\nimport React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport { Drafty, Tinode } from 'tinode-sdk';\n\nimport Contact from './contact.jsx';\nimport ContactAction from './contact-action.jsx';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\nimport { MESSAGE_PREVIEW_LENGTH } from '../config.js';\n\nconst messages = defineMessages({\n badge_you: {\n id: 'badge_you',\n defaultMessage: 'you',\n description: 'Badge for indicating the current user'\n },\n badge_owner: {\n id: 'badge_owner',\n defaultMessage: 'owner',\n description: 'Badge for indicating the owner'\n }\n});\n\nclass ContactList extends React.Component {\n render() {\n const { formatMessage } = this.props.intl;\n const showCheckmark = Array.isArray(this.props.topicSelected);\n const contactNodes = [];\n let contactsCount = 0;\n if (this.props.contacts && this.props.contacts.length > 0) {\n this.props.contacts.forEach(c => {\n if (c.action) {\n // Action item\n contactNodes.push(\n );\n } else {\n // Normal contact\n const key = this.props.showMode ? c.user : (c.topic || c.user);\n // If filter function is provided, filter out the items\n // which don't satisfy the condition.\n if (this.props.filterFunc && this.props.filter) {\n const filterOn = [key];\n if (c.private && c.private.comment) {\n filterOn.push(('' + c.private.comment).toLowerCase());\n }\n if (c.public && c.public.fn) {\n filterOn.push(('' + c.public.fn).toLowerCase());\n }\n if (!this.props.filterFunc(this.props.filter, filterOn)) {\n return;\n }\n }\n\n const isChannel = Tinode.isChannelTopicName(key);\n const isGroup = !isChannel && Tinode.isGroupTopicName(key);\n const selected = showCheckmark ?\n (this.props.topicSelected.indexOf(key) > -1) :\n (this.props.topicSelected === key);\n const badges = [];\n if (this.props.showMode) {\n if (key == this.props.myUserId) {\n badges.push({name: formatMessage(messages.badge_you), color: 'green'});\n }\n if (c.acs && c.acs.isOwner()) {\n badges.push({name: formatMessage(messages.badge_owner), color: 'blue'});\n }\n }\n\n const comment = Array.isArray(c.private) ?\n c.private.join(',') : (c.private ? c.private.comment : null);\n let preview;\n let forwarded;\n let previewIsResponse;\n let deliveryStatus;\n if (!this.props.showMode && c.latestMessage) {\n const msg = c.latestMessage();\n if (msg) {\n forwarded = msg.head ? msg.head.forwarded : null;\n deliveryStatus = msg._status || c.msgStatus(msg, true);\n previewIsResponse = msg.from != this.props.myUserId;\n if (msg.content) {\n preview = typeof msg.content == 'string' ?\n msg.content.substr(0, MESSAGE_PREVIEW_LENGTH) :\n Drafty.preview(msg.content, MESSAGE_PREVIEW_LENGTH);\n }\n }\n }\n\n contactNodes.push(\n \n );\n contactsCount ++;\n }\n }, this);\n }\n\n return (\n
    \n {contactsCount == 0 ?\n
    \n :\n null\n }\n {contactNodes.length > 0 ?\n
      \n {contactNodes}\n
    \n :\n null\n }\n
    \n );\n }\n};\n\nexport default injectIntl(ContactList);\n","// A single topic or user.\nimport React from 'react';\nimport { FormattedMessage, injectIntl } from 'react-intl';\n\nimport ContactBadges from './contact-badges.jsx';\nimport LetterTile from './letter-tile.jsx';\nimport UnreadBadge from './unread-badge.jsx';\n\nimport { Drafty } from 'tinode-sdk';\n\nimport { previewFormatter } from '../lib/formatters.js';\nimport { deliveryMarker } from '../lib/utils.js';\n\nclass Contact extends React.Component {\n constructor(props) {\n super(props);\n\n this.handleClick = this.handleClick.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n }\n\n handleClick(e) {\n e.preventDefault();\n e.stopPropagation();\n if (this.props.onSelected) {\n // Index this.props.index is used by GroupManager.\n this.props.onSelected(this.props.item, this.props.index);\n }\n }\n\n handleContextClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.showContextMenu({ topicName: this.props.item, y: e.pageY, x: e.pageX });\n }\n\n render() {\n let title = this.props.title;\n if (!title) {\n title = ;\n } else if (title.length > 30) {\n // FIXME: this is probably wrong for RTL languages.\n title = title.substring(0, 28) + '…';\n }\n const online = this.props.now ? 'online' : 'offline';\n const avatar = this.props.avatar ? this.props.avatar : true;\n const badges = this.props.badges ? this.props.badges.slice() : [];\n const icon_badges = [];\n if (this.props.isVerified) {\n icon_badges.push({icon: 'verified', color: 'verified-color'});\n }\n if (this.props.isStaff) {\n icon_badges.push({icon: 'staff', color: 'staff-color'});\n }\n if (this.props.isDangerous) {\n icon_badges.push({icon: 'dangerous', color: 'danger-color'});\n }\n if (this.props.acs) {\n if (this.props.showMode) {\n badges.push({name: this.props.acs.getMode(), key: 'mode'});\n }\n if (this.props.acs.isMuted()) {\n icon_badges.push({icon: 'muted'});\n }\n if (!this.props.acs.isJoiner()) {\n icon_badges.push({icon: 'banned'});\n }\n }\n\n // The this.props.preview contains alreay shortened Drafty or string.\n let preview;\n if (typeof this.props.preview == 'string') {\n preview = this.props.preview;\n } else if (Drafty.isValid(this.props.preview)) {\n preview = React.createElement(React.Fragment, null, Drafty.format(this.props.preview, previewFormatter,\n {formatMessage: this.props.intl.formatMessage, previewIsResponse: this.props.previewIsResponse}));\n } else if (this.props.preview) {\n preview =\n <>warning_amber \n \n ;\n }\n\n const icon = deliveryMarker(this.props.received);\n const marker = icon ? {icon.name} : null;\n const titleClass = 'contact-title' + (this.props.deleted ? ' deleted' : '');\n\n return (\n
  • \n
    \n \n {this.props.deleted ? cancel :\n this.props.showOnline ? :\n (this.props.showCheckmark && this.props.selected) ?\n check_circle\n : null}\n
    \n
    \n
    {title}\n {this.props.isGroup ? group : null}\n {this.props.isChannel ? \"channel\" : null}\n \n {!this.props.deleted ? : null}\n
    \n {this.props.showMode ?\n :\n this.props.small ? null :
    {marker}{preview || this.props.comment || '\\u00A0'}
    }\n
    \n {this.props.showContextMenu ?\n \n \n expand_more\n \n : null}\n
  • \n );\n }\n};\n\nexport default injectIntl(Contact);\n","// Context Menu: popup/dropdown menu.\nimport React from 'react';\nimport { injectIntl, defineMessages } from 'react-intl';\n\nimport { REM_SIZE } from '../config.js';\n\nconst messages = defineMessages({\n info: {\n id: 'menu_item_info',\n defaultMessage: 'Info',\n description: 'Show extended topic information'\n },\n clear_messages: {\n id: 'menu_item_clear_messages',\n defaultMessage: 'Clear messages',\n description: 'Delete all messages'\n },\n clear_for_all: {\n id: 'menu_item_clear_messages_for_all',\n defaultMessage: 'Clear for All',\n description: 'Delete all message(s) for all members'\n },\n delete: {\n id: 'menu_item_delete',\n defaultMessage: 'Delete',\n description: 'Delete selected messages'\n },\n delete_for_all: {\n id: 'menu_item_delete_for_all',\n defaultMessage: 'Delete for All',\n description: 'Delete selected message(s) for all members'\n },\n send_retry: {\n id: 'menu_item_send_retry',\n defaultMessage: 'Retry',\n description: 'Retry sending message'\n },\n mute: {\n id: 'menu_item_mute',\n defaultMessage: 'Mute',\n description: 'Turn off notifications'\n },\n unmute: {\n id: 'menu_item_unmute',\n defaultMessage: 'Unmute',\n description: 'Turn notifications on'\n },\n reply: {\n id: 'menu_item_reply',\n defaultMessage: 'Reply',\n description: 'Reply to message'\n },\n forward: {\n id: 'menu_item_forward',\n defaultMessage: 'Forward',\n description: 'Forward message'\n },\n edit: {\n id: 'menu_item_edit',\n defaultMessage: 'Edit',\n description: 'Edit message'\n },\n topic_delete: {\n id: 'menu_item_delete_topic',\n defaultMessage: 'Delete',\n description: 'Delete entire topic'\n },\n topic_delete_warning: {\n id: 'topic_delete_warning',\n defaultMessage: 'Are you sure you want to delete this conversation? It cannot be undone.',\n description: 'Alert warning when deleting entire topic'\n },\n delete_messages_warning: {\n id: 'delete_messages_warning',\n defaultMessage: 'Are you sure you want to delete all messages for everyone? It cannot be undone.',\n description: 'Alert dialog warning when hard-deleting all messages.'\n },\n unblock: {\n id: 'menu_item_unblock',\n defaultMessage: 'Unblock',\n description: 'Unblock topic or user'\n },\n // Generic string suitable for either topic or user.\n block: {\n id: 'menu_item_block',\n defaultMessage: 'Block',\n description: 'Block topic or user'\n },\n topic_block_warning: {\n id: 'topic_block_warning',\n defaultMessage: 'Are you sure you want to block this conversation?',\n description: 'Alert warning when blocking a topic.'\n },\n member_delete: {\n id: 'menu_item_member_delete',\n defaultMessage: 'Remove',\n description: 'Remove user from topic'\n },\n archive: {\n id: 'menu_item_archive_topic',\n defaultMessage: 'Archive',\n description: 'Move topic from the list of active chats to archive'\n },\n unarchive: {\n id: 'menu_item_restore_topic',\n defaultMessage: 'Restore',\n description: 'Restore topic from archive'\n },\n edit_permissions: {\n id: 'menu_item_edit_permissions',\n defaultMessage: 'Edit permissions',\n description: 'Menu item [Edit permissions]'\n },\n clear_messages_warning: {\n id: 'clear_messages_warning',\n defaultMessage: 'Are you sure you want to clear all messages? It cannot be undone.',\n description: 'Alert dialog warning when deleting all messages.'\n },\n pin_message: {\n id: 'pin_message',\n defaultMessage: 'Pin',\n description: 'Menu item [Pin] for pinning message to the top.'\n },\n unpin_message: {\n id: 'unpin_message',\n defaultMessage: 'Unpin',\n description: 'Menu item [Unpin] for un-pinning the message.'\n },\n});\n\nclass ContextMenu extends React.Component {\n constructor(props) {\n super(props);\n\n this.selfRef = React.createRef();\n\n const {formatMessage} = props.intl;\n\n this.handlePageClick = this.handlePageClick.bind(this);\n this.handleEscapeKey = this.handleEscapeKey.bind(this);\n this.handleClick = this.handleClick.bind(this);\n\n // Preconfigured menu items.\n this.MenuItems = {\n 'topic_info': {\n id: 'topic_info',\n title: formatMessage(messages.info),\n handler: null\n },\n 'messages_clear': {\n id: 'messages_clear',\n title: formatMessage(messages.clear_messages),\n handler: (params, errorHandler) => {\n return props.onShowAlert(\n formatMessage(messages.clear_messages), // title\n formatMessage(messages.clear_messages_warning), // content\n (_ => { this.deleteMessages(true, false, params, errorHandler); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n },\n 'messages_clear_hard': {\n id: 'messages_clear_hard',\n title: formatMessage(messages.clear_for_all),\n handler: (params, errorHandler) => {\n return props.onShowAlert(\n formatMessage(messages.clear_for_all), // title\n formatMessage(messages.delete_messages_warning), // content\n (_ => { return this.deleteMessages(true, true, params, errorHandler); }),\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n },\n 'message_delete': {\n id: 'message_delete',\n title: formatMessage(messages.delete),\n handler: (params, errorHandler) => {\n return this.deleteMessages(false, false, params, errorHandler);\n }\n },\n 'message_delete_hard': {\n id: 'message_delete_hard',\n title: formatMessage(messages.delete_for_all),\n handler: (params, errorHandler) => {\n return this.deleteMessages(false, true, params, errorHandler);\n }\n },\n 'menu_item_send_retry': {\n id: 'menu_item_send_retry',\n title: formatMessage(messages.send_retry),\n handler: (params, errorHandler) => {\n return this.retryMessage(params, errorHandler);\n }\n },\n 'menu_item_reply': {\n id: 'menu_item_reply',\n title: formatMessage(messages.reply),\n handler: (params, errorHandler) => {\n return this.replyToMessage(params, errorHandler);\n }\n },\n 'menu_item_forward': {\n id: 'menu_item_forward',\n title: formatMessage(messages.forward),\n handler: _ => {} /* the action is taken directly in tinode-web */\n },\n 'menu_item_edit': {\n id: 'menu_item_edit',\n title: formatMessage(messages.edit),\n handler: (params, errorHandler) => {\n return this.editMessage(params, errorHandler);\n }\n },\n 'menu_item_pin': {\n id: 'menu_item_pin',\n title: formatMessage(messages.pin_message),\n handler: (params, errorHandler) => {\n return this.pinMessage(true, params, errorHandler);\n }\n },\n 'menu_item_unpin': {\n id: 'menu_item_unpin',\n title: formatMessage(messages.unpin_message),\n handler: (params, errorHandler) => {\n return this.pinMessage(false, params, errorHandler);\n }\n },\n 'topic_unmute': {\n id: 'topic_unmute',\n title: formatMessage(messages.unmute),\n handler: this.topicPermissionSetter.bind(this, '+P')\n },\n 'topic_mute': {\n id: 'topic_mute',\n title: formatMessage(messages.mute),\n handler: this.topicPermissionSetter.bind(this, '-P')\n },\n 'topic_unblock': {\n id: 'topic_unblock',\n title: formatMessage(messages.unblock),\n handler: this.topicPermissionSetter.bind(this, '+JP')\n },\n 'topic_block': {\n id: 'topic_block',\n title: formatMessage(messages.block),\n handler: (params, errorHandler) => {\n return props.onShowAlert(\n formatMessage(messages.block), // title\n formatMessage(messages.topic_block_warning), // content\n (_ => this.topicPermissionSetter('-JP', params, errorHandler).then(ctrl => {\n this.props.onTopicRemoved(params.topicName);\n return ctrl;\n })),\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n },\n 'topic_delete': {\n id: 'topic_delete',\n title: formatMessage(messages.topic_delete),\n handler: (params, errorHandler) => {\n return props.onShowAlert(\n formatMessage(messages.topic_delete), // title\n formatMessage(messages.topic_delete_warning), // content\n (_ => {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found: \", params.topicName);\n return;\n }\n return topic.delTopic(true).catch(err => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }),\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n },\n 'topic_archive': {\n id: 'topic_archive',\n title: formatMessage(messages.archive),\n handler: (params, errorHandler) => {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found: \", params.topicName);\n return;\n }\n return topic.archive(true).catch(err => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n },\n 'topic_restore': {\n id: 'topic_restore',\n title: formatMessage(messages.unarchive),\n handler: (params, errorHandler) => {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found: \", params.topicName);\n return;\n }\n return topic.archive(false).catch(err => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n },\n // menu_item_edit_permissions is defined elsewhere.\n 'permissions': {\n id: 'permissions',\n title: formatMessage(messages.edit_permissions),\n handler: null\n },\n 'member_delete': {\n id: 'member_delete',\n title: formatMessage(messages.member_delete),\n handler: (params, errorHandler) => {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic || !params.user) {\n console.warn(\"Topic or user not found: '\" + params.topicName + \"', '\" + params.user + \"'\");\n return;\n }\n return topic.delSubscription(params.user).catch(err => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n },\n 'member_mute': {\n id: 'member_mute',\n title: formatMessage(messages.mute),\n handler: this.topicPermissionSetter.bind(this, '-P')\n },\n 'member_unmute': {\n id: 'member_unmute',\n title: formatMessage(messages.unmute),\n handler: this.topicPermissionSetter.bind(this, '+P')\n },\n 'member_block': {\n id: 'member_block',\n title: formatMessage(messages.block),\n handler: this.topicPermissionSetter.bind(this, '-JP')\n },\n 'member_unblock': {\n id: 'member_unblock',\n title: formatMessage(messages.unblock),\n handler: this.topicPermissionSetter.bind(this, '+JP')\n },\n };\n }\n\n componentDidMount() {\n document.addEventListener('mousedown', this.handlePageClick, false);\n document.addEventListener('keyup', this.handleEscapeKey, false);\n }\n\n componentWillUnmount() {\n document.removeEventListener('mousedown', this.handlePageClick, false);\n document.removeEventListener('keyup', this.handleEscapeKey, false);\n }\n\n handlePageClick(e) {\n if (this.selfRef.current.contains(e.target)) {\n return;\n }\n e.preventDefault();\n e.stopPropagation();\n this.props.hide();\n }\n\n handleEscapeKey(e) {\n if (e.keyCode === 27) {\n this.props.hide();\n }\n }\n\n handleClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.hide();\n let item = this.props.items[e.currentTarget.dataset.id];\n if (typeof item == 'string') {\n item = this.MenuItems[item];\n }\n\n if (!item) {\n console.error(\"Invalid menu item ID\", e.currentTarget.dataset.id);\n } else {\n this.props.onAction(\n item.id,\n item.handler(this.props.params, this.props.onError),\n this.props.params);\n }\n }\n\n // Menu Actions\n\n deleteMessages(all, hard, params, errorHandler) {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found: \", params.topicName);\n return;\n }\n\n // We don't know if the message is still pending (e.g. attachment is being uploaded),\n // so try cancelling first. No harm if we can't cancel.\n // The message can be cancelled if transmission to the server has not\n // started yet or if the message send has failed.\n if (!all && topic.cancelSend(params.seq)) {\n return;\n }\n\n const promise = all ?\n topic.delMessagesAll(hard) :\n params.replace > 0 ?\n topic.delMessagesEdits(params.replace, hard) :\n topic.delMessagesList([params.seq], hard);\n\n return promise.catch(err => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n\n // Retries sending failed message.\n retryMessage(params, errorHandler) {\n const topic = this.props.tinode.getTopic(params.topicName);\n // Remove the existing message entry.\n if (!topic || !topic.flushMessage(params.seq)) {\n return;\n }\n const msg = topic.createMessage(params.content, false);\n return topic.publishDraft(msg).catch(err => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n\n // Pin or unpin the message.\n pinMessage(pin, params, errorHandler) {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n return;\n }\n topic.pinMessage(params.seq, pin)\n .catch(err => errorHandler ? errorHandler(err.message, 'err') : null);\n }\n\n // Function is used by context menu to set permissions.\n topicPermissionSetter(mode, params, errorHandler) {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found\", params.topicName);\n return;\n }\n\n let result = topic.updateMode(params.user, mode);\n if (errorHandler) {\n result = result.catch(err => errorHandler(err.message, 'err'));\n }\n return result;\n }\n\n replyToMessage(params, errorHandler) {\n params.pickReply(params.seq, params.content, params.userFrom, params.userName, errorHandler);\n }\n\n editMessage(params, errorHandler) {\n params.editMessage(params.replace || params.seq, params.content, errorHandler);\n }\n\n render() {\n const menu = [];\n let count = 0;\n this.props.items.forEach(item => {\n if (typeof item == 'string') {\n item = this.MenuItems[item];\n }\n if (item && item.title) {\n menu.push(\n item.title == '-' ?\n
  • \n :\n
  • {item.title}
  • \n );\n }\n count++;\n });\n\n // Ensure that menu is inside the app-container.\n const hSize = 12 * REM_SIZE;\n const vSize = REM_SIZE * (0.7 + menu.length * 2.5);\n const left = (this.props.bounds.right - this.props.clickAt.x < hSize) ?\n (this.props.clickAt.x - this.props.bounds.left - hSize) :\n (this.props.clickAt.x - this.props.bounds.left);\n const top = (this.props.bounds.bottom - this.props.clickAt.y < vSize) ?\n (this.props.clickAt.y - this.props.bounds.top - vSize) :\n (this.props.clickAt.y - this.props.bounds.top);\n\n const position = {\n left: left + 'px',\n top: top + 'px'\n };\n\n return (\n
      \n {menu}\n
    \n );\n }\n}\n\nexport default injectIntl(ContextMenu);\n","// Image zoom and crop widget.\n\nimport React from 'react';\n\nconst DEFAULT_MAX_ZOOM = 2.5;\n\nexport default class Cropper extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n // Coordinates of the top left corner of the image in container coordinates.\n panX: 0,\n panY: 0,\n // Origin of the zoom in image coordinates.\n originX: 0,\n originY: 0,\n // Zoom scale.\n zoom: 1,\n // Zoom min and max.\n minZoom: 0,\n maxZoom: DEFAULT_MAX_ZOOM,\n };\n\n // References to DOM elements for hooking up events and getting screen dimensions.\n // The transparent element which captures mouse moves (moves with the image).\n this.overlay = React.createRef();\n // The image cutout window or view port (static).\n this.cutout = React.createRef();\n // Scaled and translated image preview.\n this.preview = React.createRef();\n // The main container (static).\n this.boundingBox = React.createRef();\n\n // The original image width and height before any scaling.\n this.imageWidth = 0;\n this.imageHeight = 0;\n\n // Mouse position when dragging.\n this.mouseX = 0\n this.mouseY = 0;\n // Length of the previous mouse move when dragging.\n this.prevDistance = 0;\n\n // Bounding rectangles of static elements.\n this.cutoutRect = {};\n this.bBoxRect = {};\n // Center of the bounding box.\n this.originX = 0;\n this.originY = 0;\n\n this.initScaling = this.initScaling.bind(this);\n this.onZoom = this.onZoom.bind(this);\n this.handleZoom = this.handleZoom.bind(this);\n this.mouseDown = this.mouseDown.bind(this);\n this.mouseUp = this.mouseUp.bind(this);\n this.mouseMove = this.mouseMove.bind(this);\n this.mouseTouch = this.mouseTouch.bind(this);\n this.positionAll = this.positionAll.bind(this);\n this.translate = this.translate.bind(this);\n }\n\n componentDidMount() {\n this.overlay.current.addEventListener('mousedown', this.mouseDown, { passive: true });\n this.overlay.current.addEventListener('touchstart', this.mouseDown, { passive: true });\n\n // The rectangle position is in viewport coordinates.\n this.bBoxRect = this.boundingBox.current.getBoundingClientRect();\n // Center of the bounding box in container coordinates.\n this.originX = this.bBoxRect.width / 2;\n this.originY = this.bBoxRect.height / 2;\n\n // The rectangle position is in viewport coordinates.\n this.cutoutRect = this.cutout.current.getBoundingClientRect();\n }\n\n componentWillUnmount() {\n this.overlay.current.removeEventListener('mousedown', this.mouseDown);\n this.overlay.current.removeEventListener('touchstart', this.mouseDown);\n }\n\n // Position all elements.\n positionAll(panX, panY, zoom) {\n // Zoom origin in image preview coordinates.\n this.setState({\n panX: panX,\n panY: panY,\n zoom: zoom,\n originX: this.originX - panX,\n originY: this.originY - panY,\n });\n\n // Pass cut out coordinates to caller.\n const left = (this.originX - panX) * zoom - this.originX;\n const top = (this.originY - panY) * zoom - this.originY;\n this.props.onChange(\n (left + this.cutoutRect.left - this.bBoxRect.left) / zoom,\n (top + this.cutoutRect.top - this.bBoxRect.top) / zoom,\n this.cutoutRect.width / zoom,\n this.cutoutRect.height / zoom,\n zoom);\n }\n\n // Check if new location is within the limits.\n static checkBound(currPan, img, cutout, delta) {\n let nextDiff = Math.min(0, cutout[0] - img[0] - delta, img[1] - cutout[1] + delta);\n if (nextDiff == 0) {\n // Cutout is completely within the image.\n currPan += delta;\n } else if (Math.min(0, cutout[0] - img[0], img[1] - cutout[1]) < nextDiff) {\n // Cutout is outside of the range but closer to the bound.\n currPan += delta;\n }\n return currPan;\n }\n\n initScaling() {\n // Initialize components.\n const imgRect = this.preview.current.getBoundingClientRect();\n\n this.imageWidth = imgRect.width;\n this.imageHeight = imgRect.height;\n\n // Set zoom slider's min and max values. Make sure the scaled image cannot be smaller than the cutout.\n const minZoom = Math.max(this.cutoutRect.width / imgRect.width, this.cutoutRect.height / imgRect.height);\n this.setState({\n minZoom: minZoom,\n maxZoom: Math.max(DEFAULT_MAX_ZOOM, minZoom + 1)\n });\n\n // Initial zoom level fills the bounding box at the smallest image dimension and overflows the largest, i.e. \"fill\" not \"fit\".\n const zoom = Math.max(this.bBoxRect.width / imgRect.width, this.bBoxRect.height / imgRect.height);\n // Converting from viewport coordinates to container, then panning.\n const panX = this.cutoutRect.left - this.bBoxRect.left -\n (imgRect.width - this.cutoutRect.width) / 2;\n const panY = this.cutoutRect.top - this.bBoxRect.top -\n (imgRect.height - this.cutoutRect.height) / 2;\n\n this.positionAll(panX, panY, zoom);\n }\n\n onZoom(e) {\n this.handleZoom(e.target.value);\n }\n\n handleZoom(zoom) {\n let panX = this.state.panX;\n let panY = this.state.panY;\n\n // Ensure that the image at the new zoom is not outside of the cutout boundaries.\n // Calculate image coordinates at the new zoom.\n const imgLeft = this.originX - (this.originX - panX) * zoom;\n const imgRight = imgLeft + this.imageWidth * zoom;\n // Cutout in the same coordinates as the image.\n const coLeft = this.cutoutRect.left - this.bBoxRect.left;\n const coRight = coLeft + this.cutoutRect.width;\n if (coLeft < imgLeft) {\n panX -= imgLeft - coLeft;\n } else if (coRight > imgRight) {\n panX += coRight - imgRight;\n }\n const imgTop = this.originY - (this.originY - panY) * zoom;\n const imgBottom = imgTop + this.imageHeight * zoom;\n const coTop = this.cutoutRect.top - this.bBoxRect.top;\n const coBottom = coTop + this.cutoutRect.height;\n if (coTop < imgTop) {\n panY -= imgTop - coTop;\n } else if (coBottom > imgBottom) {\n panY += coBottom - imgBottom;\n }\n\n this.positionAll(panX, panY, zoom);\n }\n\n mouseDown(e) {\n if (e.touches) {\n this.mouseX = e.touches[0].pageX;\n this.mouseY = e.touches[0].pageY;\n } else {\n this.mouseX = e.pageX;\n this.mouseY = e.pageY;\n }\n\n window.addEventListener('mousemove', this.mouseMove, { passive: false });\n window.addEventListener('touchmove', this.mouseTouch, { passive: false });\n window.addEventListener('mouseup', this.mouseUp, { passive: true });\n window.addEventListener('touchend', this.mouseUp, { passive: true });\n // Disable text selection in the entire document.\n document.body.style['userSelect'] = 'none';\n }\n\n // Perform image panning.\n translate(pageX, pageY) {\n const dX = pageX - this.mouseX;\n const dY = pageY - this.mouseY;\n\n this.mouseX = pageX;\n this.mouseY = pageY;\n\n // Make sure the image is within the cutout window.\n const imgRect = this.preview.current.getBoundingClientRect();\n\n // Check if the new position is within the boundaries, and if not if it's closer to them.\n let panX = Cropper.checkBound(this.state.panX, [imgRect.left, imgRect.right],\n [this.cutoutRect.left, this.cutoutRect.right], dX);\n let panY = Cropper.checkBound(this.state.panY, [imgRect.top, imgRect.bottom],\n [this.cutoutRect.top, this.cutoutRect.bottom], dY);\n\n this.positionAll(panX, panY, this.state.zoom);\n }\n\n // Image panning.\n mouseMove(e) {\n e.preventDefault();\n this.translate(e.pageX, e.pageY);\n }\n\n mouseTouch(e) {\n e.preventDefault();\n\n if (e.touches.length == 1) {\n this.translate(e.touches[0].pageX, e.touches[0].pageY);\n return;\n }\n\n // Image zooming by pinching.\n const [touch0, touch1] = e.touches;\n const distance = Math.sqrt((touch0.pageX - touch1.pageX) * (touch0.pageX - touch1.pageX) +\n (touch0.pageY - touch1.pageY) * (touch0.pageY - touch1.pageY));\n\n if (!this.prevDistance) {\n this.prevDistance = distance / this.state.zoom;\n }\n\n let scale = (distance / this.prevDistance);\n this.handleZoom(Math.max(this.minZoom, Math.min(this.maxZoom, scale)));\n }\n\n mouseUp(e) {\n window.removeEventListener('mousemove', this.mouseMove);\n window.removeEventListener('touchmove', this.mouseTouch);\n window.removeEventListener('mouseup', this.mouseUp);\n window.removeEventListener('touchend', this.mouseUp);\n // Re-enable text selection.\n document.body.style['userSelect'] = '';\n\n this.positionAll(this.state.panX, this.state.panY, this.state.zoom);\n }\n\n render() {\n // transform3d: position and scale.\n const t3d = `translate3d(${this.state.panX}px, ${this.state.panY}px, 0) scale(${this.state.zoom})`;\n // transformOrigin: zoom origin.\n const orig = `${this.state.originX}px ${this.state.originY}px`;\n\n // Overlay position and size are exactly equal to the position and size of the transformed image\n // except it uses different coordinates.\n const overlay = {\n top: `${this.originY - this.state.originY * this.state.zoom}px`,\n left: `${this.originX - this.state.originX * this.state.zoom}px`,\n width: `${this.imageWidth * this.state.zoom}px`,\n height: `${this.imageHeight * this.state.zoom}px`\n };\n return (\n
    \n
    \n \"\"\n\n
    \n
    \n
    \n
    \n \n
    \n
    \n );\n }\n}\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\nimport SendMessage from '../widgets/send-message.jsx';\n\nimport { bytesToHumanSize, shortenFileName } from '../lib/strformat.js';\n\n// Get material icon name from mime type.\nfunction iconFromMime(mime) {\n // If more icons become available in material icons, add them to this mime-to-icon mapping.\n const mimeToIcon = {default: 'insert_drive_file', image: 'image', text: 'description', video: 'theaters'};\n\n return mimeToIcon[mime] || mimeToIcon[(mime || '').split('/')[0]] || mimeToIcon['default'];\n}\n\nexport default class DocPreview extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleSendDoc = this.handleSendDoc.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n }\n\n componentDidMount() {\n document.addEventListener('keydown', this.handleKeyDown);\n }\n\n componentWillUnmount() {\n document.removeEventListener('keydown', this.handleKeyDown);\n }\n\n handleKeyDown(e) {\n e.preventDefault();\n if (e.key === 'Escape') {\n this.props.onClose();\n }\n }\n\n handleSendDoc(caption) {\n this.props.onClose();\n this.props.onSendMessage(this.props.content.file);\n }\n\n render() {\n if (!this.props.content) {\n return null;\n }\n return (\n
    \n \n
    \n
    \n {iconFromMime(this.props.content.type)}\n
    {shortenFileName(this.props.content.name, 24) || '-'}
    \n
    {this.props.content.type || 'application/octet-stream'}
    \n
    {bytesToHumanSize(this.props.content.size)}
    \n
    \n
    \n \n
    \n );\n }\n};\n","import React from 'react';\n\nimport MenuCancel from './menu-cancel.jsx';\n\nexport default class ErrorPanel extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n show: false,\n };\n\n this.hide = this.hide.bind(this);\n }\n\n componentDidUpdate(prevProps) {\n if (prevProps.level !== this.props.level) {\n this.setState({\n show: !(!this.props.level)\n });\n }\n }\n\n hide() {\n this.setState({show: false});\n if (this.props.onClearError) {\n this.props.onClearError();\n }\n }\n\n render() {\n const icons = {err: 'error', warn: 'warning', info: 'info'}\n const level = icons[this.props.level] || '';\n const className = 'info-box ' + level;\n return (\n
    \n
    {level}
    \n \n {this.props.text}\n {this.props.action ?\n <>\n {e.preventDefault(); this.props.action();}}>\n {this.props.actionText}\n \n \n : null}\n \n
    \n
    \n );\n }\n};\n","// File uload/download progress indicator with a cancel inside.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class FileProgress extends React.PureComponent {\n render() {\n return (\n
    \n
    \n {this.props.progress < 0.999 ?\n {e.preventDefault(); this.props.onCancel();}}>\n close \n \n :\n \n }\n
    \n );\n }\n}\n","// Forward Menu: message forwarding popup/dropdown menu.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport ContactList from './contact-list.jsx';\nimport SearchContacts from './search-contacts.jsx';\n\nexport default class ForwardDialog extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n query: null\n };\n\n this.handleEscapeKey = this.handleEscapeKey.bind(this);\n this.handleClose = this.handleClose.bind(this);\n\n this.handleSearchContacts = this.handleSearchContacts.bind(this);\n this.handleContactSelected = this.handleContactSelected.bind(this);\n }\n\n componentDidMount() {\n this.props.onInitFind();\n }\n\n handleEscapeKey(e) {\n if (e.keyCode === 27) {\n // Not forwarding the message.\n this.props.hide(false);\n }\n }\n\n handleClose(e) {\n e.preventDefault();\n this.props.hide(false);\n }\n\n handleSearchContacts(query) {\n this.setState({ query: Tinode.isNullValue(query) ? null : query });\n this.props.onSearchContacts(query);\n }\n\n handleContactSelected(uid) {\n this.props.onTopicSelected(uid);\n this.props.hide(true);\n }\n\n render() {\n let contacts = this.state.query != null ? this.props.searchResults : this.props.contacts;\n // Filter out contacts without a 'W' or 'J' permissions as well as the current topic.\n contacts = contacts.filter((c) => {\n return (c.name != this.props.topicSelected) && c.acs.isJoiner() && c.acs.isWriter();\n });\n\n return (\n
    \n
    \n
    \n
    \n \n
    \n {\n (search_placeholder) => \n }\n {\n (not_found_placeholder) => \n }\n
    \n
    \n );\n }\n}\n","// GroupMembers: control for managing a list of group members.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport ChipInput from './chip-input.jsx';\nimport ContactList from './contact-list.jsx';\n\nconst messages = defineMessages({\n no_contacts: {\n id: 'no_contacts',\n defaultMessage: 'You have no contacts :-(',\n description: 'Shown in ContactsView when the user has no contacts'\n },\n contacts_not_found_short: {\n id: 'contacts_not_found_short',\n defaultMessage: \"No contacts match ''{query}''\",\n description: 'Shown in ContactsView when search returned no results'\n }\n});\n\nclass GroupManager extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n // Array of topic members\n members: props.members,\n index: GroupManager.indexMembers(props.members),\n staticMembers: GroupManager.staticMembers(props.members, props.keepInitialMembers, props.requiredMember),\n contactFilter: '',\n noContactsMessage: props.intl.formatMessage(messages.no_contacts),\n selectedContacts: GroupManager.selectedContacts(props.members)\n };\n\n this.handleContactSelected = this.handleContactSelected.bind(this);\n this.handleMemberRemoved = this.handleMemberRemoved.bind(this);\n this.handleContactFilter = this.handleContactFilter.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n static indexMembers(members) {\n let index = {};\n members.forEach(m => {\n index[m.user] = {delta: 0, present: true}; // Delta: 0 unchanged, +1 added, -1 removed\n });\n return index;\n }\n\n static staticMembers(members, keepInitial, requiredMember) {\n let stat = [];\n members.forEach(m => {\n if (keepInitial || m.user == requiredMember) {\n stat.push(m.user);\n }\n });\n return stat;\n }\n\n static selectedContacts(members) {\n let sel = [];\n members.forEach(m => {\n sel.push(m.user);\n });\n return sel;\n }\n\n handleContactSelected(userId, index) {\n let status = this.state.index[userId];\n if (status) {\n if (status.present) {\n // Prevent duplicate members\n return;\n }\n status.delta += 1;\n status.present = true;\n } else {\n status = {delta: 1, present: true};\n }\n\n let m = this.state.members.slice();\n m.push(this.props.contacts[index]);\n\n const sel = GroupManager.selectedContacts(m);\n\n const i = this.state.index;\n i[userId] = status;\n\n this.setState({members: m, index: i, selectedContacts: sel});\n }\n\n handleMemberRemoved(userId, index) {\n const status = this.state.index[userId];\n if (!status || !status.present) {\n return;\n }\n status.present = false;\n status.delta -= 1;\n\n let m = this.state.members.slice();\n m.splice(index, 1);\n\n const sel = GroupManager.selectedContacts(m);\n\n const i = this.state.index;\n i[userId] = status;\n\n this.setState({members: m, index: i, selectedContacts: sel});\n }\n\n handleContactFilter(val) {\n const {formatMessage} = this.props.intl;\n const msg = !val ?\n formatMessage(messages.no_contacts) :\n formatMessage(messages.contacts_not_found_short, {query: val});\n\n this.setState({contactFilter: val, noContactsMessage: msg});\n }\n\n static doContactFiltering(filter, values) {\n if (filter) {\n for (let i=0; i= 0) {\n return true;\n }\n }\n return false;\n }\n return true;\n }\n\n handleSubmit() {\n const members = [];\n const added = [];\n const removed = [];\n\n const keys = Object.keys(this.state.index);\n keys.forEach(k => {\n if (this.state.index[k].present) {\n members.push(k);\n }\n\n if (this.state.index[k].delta > 0) {\n added.push(k);\n } else if (this.state.index[k].delta < 0) {\n removed.push(k);\n }\n });\n this.props.onSubmit(members, added, removed);\n }\n\n handleCancel() {\n this.props.onCancel();\n }\n\n render() {\n return (\n
    \n
    \n \n
    \n
    \n \n
    \n
    \n \n
    \n \n
    \n \n \n
    \n
    \n );\n }\n};\n\nexport default injectIntl(GroupManager);\n","// GroupSubs: a list of group subscribers currently online.\n// Show in the topic title bar\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { MAX_ONLINE_IN_TOPIC } from '../config.js'\n\nimport LetterTile from './letter-tile.jsx';\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\nexport default class GroupSubs extends React.Component {\n constructor(props) {\n super(props);\n }\n\n render() {\n const usersOnline = [];\n const totalCount = (this.props.subscribers || []).length;\n const countToShow = Math.min(MAX_ONLINE_IN_TOPIC, totalCount);\n\n (this.props.subscribers || []).some((sub) => {\n usersOnline.push(\n
    \n \n
    \n );\n return usersOnline.length == countToShow;\n });\n if (usersOnline.length == 0) {\n return null;\n }\n return (\n
    {usersOnline} {totalCount > countToShow ?\n \n \n : null}\n
    \n );\n }\n};\n","import React from 'react';\n\nimport { KNOWN_HOSTS } from '../config.js';\n\n/* Combobox for selecting host name */\n\nexport default class HostSelector extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n hostName: props.serverAddress,\n changed: false\n };\n\n this.handleHostNameChange = this.handleHostNameChange.bind(this);\n this.handleEditingFinished = this.handleEditingFinished.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n }\n\n handleHostNameChange(e) {\n this.setState({hostName: e.target.value, changed: true});\n }\n\n handleEditingFinished() {\n if (this.state.changed) {\n this.setState({changed: false});\n this.props.onServerAddressChange(this.state.hostName.trim());\n }\n }\n\n handleKeyDown(e) {\n if (e.key == 'Enter') {\n this.handleEditingFinished();\n }\n }\n\n render() {\n const hostOptions = [];\n for (let key in KNOWN_HOSTS) {\n let item = KNOWN_HOSTS[key];\n hostOptions.push(\n