= 0 && mode.indexOf(c) < 0) {\n // Permission is marked as inactive: hide unchecked permissions, disable checked permissions\n continue;\n }\n items.push(\n \n {names[c]} \n {skip.indexOf(c) < 0 ?\n = 0)} onChange={this.handleChange}/>\n :\n = 0)} />\n } {this.props.compare ? \n = 0)}/>\n : null}\n \n );\n }\n\n return (\n \n {this.props.userTitle ?\n
: null}\n
\n
\n {this.props.compare ?\n \n {this.props.modeTitle} \n {this.props.compareTitle} \n :\n null}\n \n {items}\n
\n
\n
\n \n \n \n \n \n \n
\n
\n );\n }\n};\n\nexport default injectIntl(PermissionsEditor);\n","// Odds and ends\n\n// Make shortcut icon appear with a green dot + show unread count in title.\nexport function updateFavicon(count) {\n var oldIcon = document.getElementById('shortcut-icon');\n if (oldIcon) {\n var head = document.head || document.getElementsByTagName('head')[0];\n var 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 head.removeChild(oldIcon);\n head.appendChild(newIcon);\n }\n document.title = (count > 0 ? '('+count+') ' : '') + 'Tinode';\n}\n\n// Create VCard which represents topic 'public' info\nexport function vcard(fn, imageDataUrl) {\n var card = null;\n\n if ((fn && fn.trim()) || imageDataUrl) {\n card = {};\n if (fn) {\n card.fn = fn.trim();\n }\n if (imageDataUrl) {\n var dataStart = imageDataUrl.indexOf(',');\n card.photo = {\n data: imageDataUrl.substring(dataStart+1),\n type: 'jpg'\n };\n }\n }\n return card;\n}\n\n// Deep-shallow compare two arrays: shallow compare each element.\nexport function arrayEqual(a, b) {\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 (var i = 0, l = a.length; i < l; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n","// TagManager: edit topic or user tags.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport ChipInput from './chip-input.jsx';\n\nimport { MIN_TAG_LENGTH } from '../config.js';\nimport { arrayEqual } from '../lib/utils.js';\n\nexport default class TagManager extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n tags: this.props.tags,\n tagInput: '',\n activated: this.props.activated\n };\n\n this.handleShowTagManager = this.handleShowTagManager.bind(this);\n this.handleTagInput = this.handleTagInput.bind(this);\n this.handleAddTag = this.handleAddTag.bind(this);\n this.handleRemoveTag = this.handleRemoveTag.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 (!arrayEqual(nextProps.tags, prevState.tags) && !prevState.activated) {\n return {tags: nextProps.tags};\n }\n return null;\n }\n\n handleShowTagManager() {\n this.setState({activated: true});\n }\n\n handleTagInput(text) {\n this.setState({tagInput: text});\n // Check if user entered ',', ' ' or ';'\n if (text.length > 0) {\n var last = text[text.length-1];\n if (last == ',' || last == ' ' || last == ';') {\n var tag = text.substr(0, text.length-1).trim();\n if (tag.length >= MIN_TAG_LENGTH) {\n this.handleAddTag(tag);\n }\n }\n }\n }\n\n handleAddTag(tag) {\n tag = tag.trim();\n if (tag.length > 0) {\n let tags = this.state.tags.slice(0);\n tags.push(tag);\n this.setState({tags: tags, tagInput: ''});\n if (this.props.onTagsChanged) {\n this.props.onTagsChanged(tags);\n }\n }\n }\n\n handleRemoveTag(tag, index) {\n var tags = this.state.tags.slice(0);\n tags.splice(index, 1);\n this.setState({tags: tags});\n if (this.props.onTagsChanged) {\n this.props.onTagsChanged(tags);\n }\n }\n\n handleSubmit() {\n let tags = this.state.tags.slice(0);\n let inp = this.state.tagInput.trim();\n if (inp.length > 0) {\n tags.push(inp);\n if (this.props.onTagsChanged) {\n this.props.onTagsChanged(tags);\n }\n }\n this.props.onSubmit(tags);\n this.setState({activated: false, tagInput: '', tags: this.props.tags});\n }\n\n handleCancel() {\n this.setState({activated: false, tagInput: '', tags: this.props.tags});\n if (this.props.onCancel) {\n this.props.onCancel();\n }\n }\n\n render() {\n var tags = [];\n if (this.state.activated) {\n this.state.tags.map(function(tag) {\n tags.push({user: tag});\n });\n } else {\n this.state.tags.map(function(tag) {\n tags.push({tag} );\n });\n if (tags.length == 0) {\n tags = (\n \n );\n }\n }\n return (\n \n
\n {this.props.title} \n
\n {this.state.activated ?\n
\n
{\n (add_tags_prompt) => \n } \n {this.props.onSubmit || this.props.onCancel ?\n
\n \n \n \n \n \n \n
\n : null}\n
\n :\n
\n }\n
\n );\n }\n};\n","// InfoView: panel with topic/user info.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport Tinode from 'tinode-sdk';\n\nimport AvatarUpload from '../widgets/avatar-upload.jsx';\nimport CheckBox from '../widgets/checkbox.jsx';\nimport ContactList from '../widgets/contact-list.jsx';\nimport GroupManager from '../widgets/group-manager.jsx';\nimport InPlaceEdit from '../widgets/in-place-edit.jsx';\nimport MenuCancel from '../widgets/menu-cancel.jsx';\nimport MoreButton from '../widgets/more-button.jsx';\nimport PermissionsEditor from '../widgets/permissions-editor.jsx';\nimport TagManager from '../widgets/tag-manager.jsx';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\nconst messages = defineMessages({\n requested: {\n id: 'requested_permissions',\n defaultMessage: 'Requested',\n description: 'Title for permissions'\n },\n granted: {\n id: 'granted_permissions',\n defaultMessage: 'Granted',\n description: 'Title for permissions'\n },\n edit_permissions: {\n id: 'menu_item_edit_permissions',\n defaultMessage: 'Edit permissions',\n description: 'Menu item [Edit permissions]'\n },\n other_user: {\n id: 'label_other_user',\n defaultMessage: 'Other',\n description: 'Label for the other user when the user is unnamed'\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 muted: false,\n address: null,\n groupTopic: undefined,\n fullName: 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 tags: [],\n showMemberPanel: false,\n showPermissionEditorFor: undefined,\n moreInfoExpanded: false,\n previousMetaDesc: undefined,\n previousSubsUpdated: undefined,\n previousTagsUpdated: undefined\n };\n\n this.resetSubs = this.resetSubs.bind(this);\n this.resetDesc = this.resetDesc.bind(this);\n this.onMetaDesc = this.onMetaDesc.bind(this);\n this.onSubsUpdated = this.onSubsUpdated.bind(this);\n this.onTagsUpdated = this.onTagsUpdated.bind(this);\n this.handleFullNameUpdate = this.handleFullNameUpdate.bind(this);\n this.handlePrivateUpdate = this.handlePrivateUpdate.bind(this);\n this.handleImageChanged = this.handleImageChanged.bind(this);\n this.handleMuted = this.handleMuted.bind(this);\n this.handlePermissionsChanged = this.handlePermissionsChanged.bind(this);\n this.handleLaunchPermissionsEditor = this.handleLaunchPermissionsEditor.bind(this);\n this.handleHidePermissionsEditor = this.handleHidePermissionsEditor.bind(this);\n this.handleShowAddMembers = this.handleShowAddMembers.bind(this);\n this.handleHideAddMembers = this.handleHideAddMembers.bind(this);\n this.handleMemberUpdateRequest = this.handleMemberUpdateRequest.bind(this);\n this.handleLeave = this.handleLeave.bind(this);\n this.handleMemberSelected = this.handleMemberSelected.bind(this);\n this.handleMoreInfo = this.handleMoreInfo.bind(this);\n this.handleTagsUpdated = this.handleTagsUpdated.bind(this);\n this.handleContextMenu = this.handleContextMenu.bind(this);\n }\n\n // No need to separately handle component mount.\n UNSAFE_componentWillReceiveProps(props) {\n var 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 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 this.resetDesc(topic, props);\n this.resetSubs(topic, props);\n }\n }\n\n componentWillUnmount() {\n var 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 topic.onTagsUpdated = this.previousTagsUpdated;\n }\n\n resetSubs(topic, props) {\n var 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 var user2 = topic.subscriber(props.topic);\n if (user2) {\n newState.modeGiven2 = user2.acs.getGiven();\n newState.modeWant2 = user2.acs.getWant();\n }\n } else {\n topic.subscribers(function(sub) {\n newState.contactList.push(sub);\n }, this);\n }\n\n this.setState(newState);\n }\n\n resetDesc(topic, props) {\n var defacs = topic.getDefaultAccess() || {};\n var acs = topic.getAccessMode();\n this.setState({\n owner: acs && acs.isOwner(),\n admin: acs && acs.isAdmin(),\n sharer: acs && (acs.isAdmin() || acs.isSharer()),\n muted: acs && acs.isMuted(),\n\n fullName: topic.public ? topic.public.fn : undefined,\n avatar: makeImageUrl(topic.public ? topic.public.photo : null),\n private: topic.private ? topic.private.comment : null,\n address: topic.name,\n groupTopic: (topic.getType() == 'grp'),\n showMemberPanel: false,\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 if (topic.getType() == 'grp' && 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 var 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() {\n var 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();\n }\n }\n\n onTagsUpdated(tags) {\n this.setState({tags: tags});\n\n if (this.previousTagsUpdated && this.previousTagsUpdated != this.onTagsUpdated) {\n this.previousTagsUpdated();\n }\n }\n\n handleFullNameUpdate(fn) {\n if (this.state.fullName !== fn) {\n this.setState({fullName: fn});\n this.props.onTopicDescUpdate(this.props.topic,\n vcard(fn, this.state.avatar),\n null);\n }\n }\n\n handlePrivateUpdate(priv) {\n if (this.state.priv !== priv) {\n this.setState({private: priv});\n this.props.onTopicDescUpdate(this.props.topic,\n null,\n priv || Tinode.DEL_CHAR);\n }\n }\n\n handleImageChanged(img) {\n this.setState({avatar: img});\n this.props.onTopicDescUpdate(this.props.topic,\n vcard(this.state.fullName, img),\n 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 handlePermissionsChanged(perm) {\n switch (this.state.showPermissionEditorFor) {\n case 'auth':\n this.props.onTopicDescUpdate(this.props.topic, null, null, {auth: perm});\n break;\n case 'anon':\n this.props.onTopicDescUpdate(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.setState({showPermissionEditorFor: undefined});\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 toSkip = this.state.groupTopic ? 'O' : 'ASDO';\n titleEdit = formatMessage(messages.requested);\n titleCompare = formatMessage(messages.granted);\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.granted);\n titleCompare = formatMessage(messages.requested);\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 let topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n var 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.granted);\n titleCompare = formatMessage(messages.requested);\n if (user.public) {\n userTitle = user.public.fn;\n userAvatar = user.public.photo;\n }\n break;\n }\n default:\n console.log(\"Unknown permission editing mode '\" + which + \"'\");\n break;\n }\n this.setState({\n showPermissionEditorFor: which,\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 }\n\n handleHidePermissionsEditor() {\n this.setState({showPermissionEditorFor: undefined});\n }\n\n handleShowAddMembers() {\n this.props.onInitFind();\n this.setState({showMemberPanel: true});\n }\n\n handleHideAddMembers() {\n this.setState({showMemberPanel: false});\n }\n\n handleMemberUpdateRequest(members, added, removed) {\n this.props.onMemberUpdateRequest(this.props.topic, added, removed);\n this.setState({showMemberPanel: false});\n }\n\n handleLeave() {\n this.props.onLeaveTopic(this.props.topic);\n }\n\n handleMemberSelected(uid) {\n this.setState({selectedContact: uid});\n }\n\n handleMoreInfo(open) {\n this.setState({moreInfoExpanded: open});\n }\n\n handleTagsUpdated(tags) {\n if (!arrayEqual(this.state.tags.slice(0), tags.slice(0))) {\n this.props.onTopicTagsUpdate(this.props.topic, tags);\n }\n }\n\n handleContextMenu(params) {\n const {formatMessage} = this.props.intl;\n const instance = this;\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 menuItems = [\n {title: formatMessage(messages.edit_permissions), handler: function() {\n instance.handleLaunchPermissionsEditor('user', params.topicName);\n }},\n 'member_delete',\n user.acs.isMuted() ? 'member_unmute' : 'member_mute',\n 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 {formatMessage} = this.props.intl;\n\n return (\n \n
\n {this.props.displayMobile ?\n
: null}\n {this.state.showMemberPanel ?\n
\n :\n this.state.showPermissionEditorFor ?\n
\n :\n
\n
\n
\n
\n \n
\n
Unknown}\n readOnly={!this.state.owner}\n value={this.state.fullName}\n onFinished={this.handleFullNameUpdate} />
\n
\n \n \n \n
\n
\n {\n (private_placeholder) => \n } \n
\n
\n
\n
\n
\n
\n
\n \n \n \n \n
\n
{\n (more) => \n } \n {this.state.moreInfoExpanded ?\n
\n
\n \n {this.state.address} \n
\n {this.state.groupTopic ?\n
\n \n \n \n \n {this.state.access}\n \n
\n :\n
\n
\n \n \n \n
\n
\n
\n \n {this.state.access}\n
\n
{this.state.fullName ? this.state.fullName : formatMessage(messages.other_user)}:\n \n {this.state.modeGiven2}\n \n
\n
\n
\n }\n {this.state.sharer && (this.state.auth || this.state.anon) ?\n
\n
\n \n \n \n
\n
\n
Auth: {this.state.admin ?\n \n {this.state.auth}\n \n :\n {this.state.auth} \n }\n
\n
Anon: {this.state.admin ?\n \n {this.state.anon}\n \n :\n {this.state.anon} \n }\n
\n
\n
\n :\n null\n }\n
\n :\n null\n }\n
\n
\n {this.state.owner ?\n
{\n (tags) => \n } \n :\n null\n }\n {this.state.owner ?
: null }\n {this.state.groupTopic ?\n
\n
\n \n \n \n
\n
\n
{\n (no_members) => \n } \n
\n :\n
\n }\n
\n }\n
\n );\n }\n};\n\nexport default injectIntl(InfoView);\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
\n close \n \n :\n
\n }\n
\n );\n }\n}\n","import React from 'react';\n\nimport FileProgress from './file-progress.jsx';\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 var downloader = this.props.tinode.getLargeFileHelper();\n this.setState({downloader: downloader});\n downloader.download(url, filename, mimetype, (loaded) => {\n this.setState({progress: loaded / this.props.size});\n }).then(() => {\n 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.uploader) {\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.uploader && !this.state.downloader &&\n !(/^(?:(?:[a-z]+:)?\\/\\/)/i.test(this.props.downloadUrl))) {\n // Relative URL. Use download helper.\n url = \"javascript:;\";\n helperFunc = (e) => {\n this.downloadFile(this.props.downloadUrl, this.props.filename, this.props.mimetype);\n };\n } else {\n url = this.props.downloadUrl;\n helperFunc = null;\n }\n return (\n \n
insert_drive_file
\n
\n
{filename} {size}
\n {this.props.uploader || this.state.downloader ?\n
\n :\n
\n }\n
\n
\n );\n }\n};\n","// Received/read indicator.\nimport React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport Tinode from 'tinode-sdk';\n\nimport { shortDateFormat } from '../lib/strformat.js';\n\nconst messages = defineMessages({\n 'sending': {\n 'id': 'message_sending',\n 'defaultMessage': 'sending...',\n 'description': 'Message being sent, in place of time stamp'\n },\n 'failed': {\n 'id': 'message_sending_failed',\n 'defaultMessage': 'failed',\n 'description': 'Failed to send message, in place of time stamp'\n }\n});\n\nclass ReceivedMarker extends React.PureComponent {\n render() {\n const {formatMessage} = this.props.intl;\n let timestamp;\n if (this.props.received <= Tinode.MESSAGE_STATUS_SENDING) {\n timestamp = formatMessage(messages.sending);\n } else if (this.props.received == Tinode.MESSAGE_STATUS_FAILED) {\n timestamp = formatMessage(messages.failed);\n } else {\n timestamp = shortDateFormat(this.props.timestamp);\n }\n\n let marker = null;\n if (this.props.received <= Tinode.MESSAGE_STATUS_SENDING) {\n marker = (access_time ); // watch face\n } else if (this.props.received == Tinode.MESSAGE_STATUS_FAILED) {\n marker = (error_outline ); // icon (!)\n } else if (this.props.received == Tinode.MESSAGE_STATUS_SENT) {\n marker = (done ); // checkmark\n } else if (this.props.received == Tinode.MESSAGE_STATUS_RECEIVED) {\n marker = (done_all ); // double checkmark\n } else if (this.props.received == Tinode.MESSAGE_STATUS_READ) {\n marker = (done_all ); // blue double checkmark\n }\n\n return (\n \n {timestamp}{'\\u00a0'}{marker}\n \n );\n }\n};\n\nexport default injectIntl(ReceivedMarker);\n","// Single message, sent or received.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\nimport { Drafty } from 'tinode-sdk'\n\nimport Attachment from './attachment.jsx';\nimport LetterTile from './letter-tile.jsx';\nimport ReceivedMarker from './received-marker.jsx'\n\nexport default class ChatMessage extends React.Component {\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.handlePreviewImage = this.handlePreviewImage.bind(this);\n this.handleFormButtonClick = this.handleFormButtonClick.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n this.handleCancelUpload = this.handleCancelUpload.bind(this);\n }\n\n handlePreviewImage(e) {\n e.preventDefault();\n this.props.onImagePreview({\n url: e.target.src,\n filename: e.target.title,\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 handleFormButtonClick(e) {\n e.preventDefault();\n console.log(e.target);\n }\n\n handleContextClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.showContextMenu({ seq: this.props.seq, y: e.pageY, x: e.pageX });\n }\n\n handleProgress(ratio) {\n this.setState({progress: ratio});\n }\n\n handleCancelUpload() {\n this.props.uploader.cancel();\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') ?\n 'bubble tip' : 'bubble';\n const avatar = this.props.userAvatar || true;\n const fullDisplay = (this.props.userFrom && 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()) {\n Drafty.attachments(content, function(att, i) {\n attachments.push( );\n }, this);\n content = React.createElement('span', null, Drafty.format(content, draftyFormatter, this));\n } else if (typeof content != 'string') {\n content = error_outline \n \n \n }\n\n return (\n \n {this.props.userFrom && this.props.response ?\n \n {fullDisplay ?\n :\n null}\n
:\n null}\n \n
\n {fullDisplay ?
{this.props.userName}
: null}\n
\n \n );\n }\n};\n\n// Convert Drafty object to a tree of React elements.\nimport { REM_SIZE } from '../config.js';\nimport { fitImageSize } from '../lib/blob-helpers.js';\n\nfunction draftyFormatter(style, data, values, key) {\n let el = Drafty.tagName(style);\n if (el) {\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch (style) {\n case 'IM':\n // Additional processing for images\n if (data) {\n attr.className = 'inline-image';\n attr.onClick = this.handlePreviewImage;\n let dim = fitImageSize(data.width, data.height,\n Math.min(this.props.viewportWidth - REM_SIZE * 4, REM_SIZE * 36), REM_SIZE * 24, false);\n attr.style = dim ? { width: dim.dstWidth + 'px', height: dim.dstHeight + 'px' } : null;\n }\n break;\n case 'BN':\n // Button\n attr.onClick = this.handleFormButtonClick;\n break;\n case 'FM':\n // Form\n attr.className = 'bot-form' + ((data && data.layout) ? ' ' + data.layout : '');\n break;\n }\n return React.createElement(el, attr, values);\n } else {\n return values;\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 static getDerivedStateFromProps(nextProps, prevState) {\n return {\n show: !(!nextProps.level)\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 = 'alert-box ' + level;\n return (\n \n );\n }\n};\n","/* GroupSubs: a list of group subscribers currently online */\n\nimport React from 'react';\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 this.state = {\n onlineSubs: props.subscribers || []\n };\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n return {\n onlineSubs: nextProps.subscribers ? nextProps.subscribers : []\n };\n }\n\n render() {\n var usersOnline = [];\n this.state.onlineSubs.map((sub) => {\n usersOnline.push(\n \n \n
\n );\n });\n return (\n {usersOnline}
\n );\n }\n};\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { REM_SIZE } from '../config.js';\nimport { fitImageSize } from '../lib/blob-helpers.js';\nimport { bytesToHumanSize } from '../lib/strformat.js';\n\nexport default class ImagePreview extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {};\n }\n\n componentDidMount() {\n this.setState({\n width: this.container.clientWidth,\n height: this.container.clientHeight\n });\n }\n\n render() {\n if (!this.props.content) {\n return null;\n }\n var instance = this;\n var dim = fitImageSize(this.props.content.width, this.props.content.height,\n this.state.width, this.state.height, false);\n var size = dim ? { width: dim.dstWidth + 'px', height: dim.dstHeight + 'px' } :\n ((this.props.content.width > this.props.content.height) ? {width: '100%'} : {height: '100%'});\n size.maxWidth = '100%';\n size.maxHeight = '100%';\n\n var filename = this.props.content.filename;\n var maxlength = (this.props.content.width / REM_SIZE) | 0;\n if (filename.length > maxlength) {\n filename = filename.slice(0, maxlength-2) + '...' + filename.slice(2-maxlength);\n }\n return (\n \n
\n
\n
\n
\n \n
\n );\n }\n};\n","import React from 'react';\n\nexport default class LoadSpinner extends React.PureComponent {\n render() {\n return (this.props.show ?\n : null);\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 var version = APP_NAME + ' (' + Tinode.getLibrary() + ')';\n return (\n \n
\n
\n \n Tinode Web \n \n
{version}
\n
{this.props.serverVersion}\n ({this.props.serverAddress})
\n
\n
\n );\n }\n};\n","// Send message form.\nimport React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\nimport { Drafty } from 'tinode-sdk';\n\nimport { KEYPRESS_DELAY, MAX_EXTERN_ATTACHMENT_SIZE, MAX_IMAGE_DIM, MAX_INBAND_ATTACHMENT_SIZE } from '../config.js';\nimport { SUPPORTED_IMAGE_FORMATS, filePasted, imageFileToBase64, imageFileScaledToBase64 } from '../lib/blob-helpers.js';\nimport { bytesToHumanSize } from '../lib/strformat.js';\n\nconst messages = defineMessages({\n 'messaging_disabled': {\n id: 'messaging_disabled_prompt',\n defaultMessage: 'Messaging disabled',\n description: 'Prompt in SendMessage in read-only topic'\n },\n 'type_new_message': {\n id: 'new_message_prompt',\n defaultMessage: 'New message',\n description: 'Prompt in SendMessage in read-only topic'\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 'cannot_initiate_upload': {\n id: 'cannot_initiate_file_upload',\n defaultMessage: 'Cannot initiate file upload.',\n description: 'Generic error messagewhen attachment fails'\n },\n});\n\nclass SendMessage extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n message: '',\n // Make initial keypress time as if it happened 5001 milliseconds in the past.\n keypressTimestamp: new Date().getTime() - KEYPRESS_DELAY - 1\n };\n\n this.handlePasteEvent = this.handlePasteEvent.bind(this);\n this.handleAttachImage = this.handleAttachImage.bind(this);\n this.handleAttachFile = this.handleAttachFile.bind(this);\n this.handleSend = this.handleSend.bind(this);\n this.handleKeyPress = this.handleKeyPress.bind(this);\n this.handleMessageTyping = this.handleMessageTyping.bind(this);\n }\n\n componentDidMount() {\n this.pasteFile.addEventListener('paste', this.handlePasteEvent, false);\n }\n\n componentWillUnmount() {\n this.pasteFile.removeEventListener('paste', this.handlePasteEvent, false)\n }\n\n handlePasteEvent(e) {\n if (this.props.disabled) {\n return;\n }\n // FIXME: handle large files too.\n if (filePasted(e,\n (bits, mime, width, height, fname) => {\n this.props.sendMessage(Drafty.insertImage(null,\n 0, mime, bits, width, height, fname));\n },\n (mime, bits, fname) => {\n this.props.sendMessage(Drafty.attachFile(null, mime, bits, fname));\n },\n this.props.onError)) {\n\n // If a file was pasted, don't paste base64 data into input field.\n e.preventDefault();\n }\n }\n\n handleAttachImage(e) {\n if (e.target.files && e.target.files.length > 0) {\n let file = e.target.files[0];\n // Check if the uploaded file is indeed an image and if it isn't too large.\n if (file.size > MAX_INBAND_ATTACHMENT_SIZE || SUPPORTED_IMAGE_FORMATS.indexOf(file.type) < 0) {\n // Convert image for size or format.\n imageFileScaledToBase64(file, MAX_IMAGE_DIM, MAX_IMAGE_DIM, false,\n // Success\n (bits, mime, width, height, fname) => {\n this.props.sendMessage(Drafty.insertImage(null,\n 0, mime, bits, width, height, fname));\n },\n // Failure\n (err) => {\n this.props.onError(err, 'err');\n });\n } else {\n // Image can be uploaded as is. No conversion is needed.\n imageFileToBase64(file,\n // Success\n (bits, mime, width, height, fname) => {\n this.props.sendMessage(Drafty.insertImage(null,\n 0, mime, bits, width, height, fname));\n },\n // Failure\n (err) => {\n this.props.onError(err, 'err');\n }\n );\n }\n }\n // Clear the value so the same file can be uploaded again.\n e.target.value = '';\n }\n\n handleAttachFile(e) {\n const {formatMessage} = this.props.intl;\n if (e.target.files && e.target.files.length > 0) {\n var file = e.target.files[0];\n if (file.size > MAX_EXTERN_ATTACHMENT_SIZE) {\n // Too large.\n this.props.onError(formatMessage(messages.file_attachment_too_large,\n {size: bytesToHumanSize(file.size), limit: bytesToHumanSize(MAX_EXTERN_ATTACHMENT_SIZE)}), 'err');\n } else if (file.size > MAX_INBAND_ATTACHMENT_SIZE) {\n // Too large to send inband - uploading out of band and sending as a link.\n let uploader = this.props.tinode.getLargeFileHelper();\n if (!uploader) {\n this.props.onError(formatMessage(messages.cannot_initiate_upload));\n return;\n }\n // Format data and initiate upload.\n let uploadCompletionPromise = uploader.upload(file);\n let msg = Drafty.attachFile(null, file.type, null, file.name, file.size, uploadCompletionPromise);\n // Pass data and the uploader to the TinodeWeb.\n this.props.sendMessage(msg, uploadCompletionPromise, uploader);\n } else {\n // Small enough to send inband.\n fileToBase64(file,\n (mime, bits, fname) => {\n this.props.sendMessage(Drafty.attachFile(null, mime, bits, fname));\n },\n this.props.onError\n );\n }\n }\n // Clear the value so the same file can be uploaded again.\n e.target.value = '';\n }\n\n handleSend() {\n var message = this.state.message.trim();\n if (message) {\n this.props.sendMessage(this.state.message.trim());\n this.setState({message: ''});\n }\n }\n\n /* Send on Enter key */\n handleKeyPress(e) {\n // Remove this if you don't want Enter to trigger send\n if (e.key === 'Enter') {\n // Have Shift-Enter insert a line break instead\n if (!e.shiftKey) {\n e.preventDefault();\n e.stopPropagation();\n\n this.handleSend();\n }\n }\n }\n\n handleMessageTyping(e) {\n var newState = {message: e.target.value};\n var now = new Date().getTime();\n if (now - this.state.keypressTimestamp > KEYPRESS_DELAY) {\n var topic = this.props.tinode.getTopic(this.props.topic);\n if (topic.isSubscribed()) {\n topic.noteKeyPress();\n }\n newState.keypressTimestamp = now;\n }\n this.setState(newState);\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n const prompt = this.props.disabled ?\n formatMessage(messages.messaging_disabled) :\n formatMessage(messages.type_new_message);\n let instance = this;\n return (\n \n );\n }\n};\n\nexport default injectIntl(SendMessage);\n","import React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport Tinode from 'tinode-sdk';\n\nimport ChatMessage from '../widgets/chat-message.jsx';\nimport ErrorPanel from '../widgets/error-panel.jsx';\nimport GroupSubs from '../widgets/group-subs.jsx';\nimport ImagePreview from '../widgets/image-preview.jsx';\nimport LetterTile from '../widgets/letter-tile.jsx';\nimport LoadSpinner from '../widgets/load-spinner.jsx';\nimport LogoView from './logo-view.jsx';\nimport SendMessage from '../widgets/send-message.jsx';\n\nimport { KEYPRESS_DELAY, MESSAGES_PAGE } from '../config.js';\nimport { makeImageUrl } from '../lib/blob-helpers.js';\nimport { shortDateFormat } from '../lib/strformat.js';\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});\n\nclass MessagesView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n messages: [],\n onlineSubs: [],\n topic: '',\n title: '',\n avatar: null,\n scrollPosition: 0,\n readOnly: props.acs ? !props.acs.isWriter() : true,\n writeOnly: props.acs ? !props.acs.isReader() : true,\n typingIndicator: false,\n imagePreview: null\n };\n\n this.propsChange = this.propsChange.bind(this);\n this.leave = this.leave.bind(this);\n this.handleScrollReference = this.handleScrollReference.bind(this);\n this.fetchMoreMessages = this.fetchMoreMessages.bind(this);\n this.handleDescChange = this.handleDescChange.bind(this);\n this.handleSubsUpdated = this.handleSubsUpdated.bind(this);\n this.handleNewMessage = this.handleNewMessage.bind(this);\n this.handleAllMessagesReceived = this.handleAllMessagesReceived.bind(this);\n this.handleInfoReceipt = this.handleInfoReceipt.bind(this);\n this.handleImagePreview = this.handleImagePreview.bind(this);\n this.handleCloseImagePreview = this.handleCloseImagePreview.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n this.handleShowContextMenuMessage = this.handleShowContextMenuMessage.bind(this);\n this.handleBackNavigation = this.handleBackNavigation.bind(this);\n }\n\n // Scroll last message into view on component update e.g. on message received.\n componentDidUpdate(prevProps, prevState) {\n if (this.messagesScroller &&\n (prevState.title != this.state.title ||\n prevState.messages.length != this.state.messages.length)) {\n this.messagesScroller.scrollTop = this.messagesScroller.scrollHeight - this.state.scrollPosition;\n }\n }\n\n componentDidMount() {\n this.propsChange(this.props);\n if (this.messagesScroller) {\n this.messagesScroller.addEventListener('scroll', this.fetchMoreMessages);\n }\n }\n\n componentWillUnmount() {\n this.leave(this.state.topic);\n if (this.messagesScroller) {\n this.messagesScroller.removeEventListener('scroll', this.fetchMoreMessages);\n }\n }\n\n UNSAFE_componentWillReceiveProps(nextProps) {\n this.propsChange(nextProps);\n }\n\n propsChange(props) {\n if (!props || !props.topic) {\n let oldTopic = this.state.topic;\n this.setState({messages: [], onlineSubs: [], topic: null}, this.leave(oldTopic));\n return;\n }\n\n if (!props.connected) {\n // connection lost, clear online subs\n this.setState({onlineSubs: []});\n return;\n }\n\n let topic = this.props.tinode.getTopic(props.topic);\n if (!topic) {\n return;\n }\n\n let newGroupTopic = Tinode.isNewGroupTopicName(props.topic);\n let tryToResubscribe = !this.props.connected && props.connected;\n\n if (props.topic != this.state.topic) {\n let msgs = [];\n let subs = [];\n\n // Bind the new topic to component.\n topic.onData = this.handleNewMessage;\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 // Unbind the previous topic from this component.\n this.leave(this.state.topic);\n\n this.handleDescChange(topic);\n topic.subscribers((sub) => {\n if (sub.online && sub.user != this.props.myUserId) {\n subs.push(sub);\n }\n });\n\n topic.messages(function(msg) {\n if (!msg.deleted) {\n msgs = msgs.concat(msg);\n }\n });\n\n this.setState({\n messages: msgs,\n onlineSubs: subs,\n topic: props.topic,\n imagePreview: null,\n scrollPosition: 0\n });\n tryToResubscribe = true;\n\n // The user switched to the new topic before the timer for\n // the previous topic has triggered, kill it.\n this.props.readTimerHandler(null);\n }\n\n this.setState({\n readOnly: props.acs ? !props.acs.isWriter() : true,\n writeOnly: props.acs ? !props.acs.isReader() : true\n });\n\n if (!topic.isSubscribed() && tryToResubscribe) {\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()\n .withLaterDesc()\n .withLaterSub()\n .withLaterData(MESSAGES_PAGE)\n .withLaterDel();\n let setQuery = newGroupTopic ? props.newGroupTopicParams : undefined;\n // Show \"loading\" spinner.\n this.setState({ fetchingMessages: true });\n topic.subscribe(getQuery.build(), setQuery)\n .then((ctrl) => {\n this.setState({topic: ctrl.topic});\n this.props.onNewTopicCreated(props.topic, ctrl.topic);\n // If there are unsent messages, try sending them now.\n topic.queuedMessages((pub) => {\n if (!pub._sending && topic.isSubscribed()) {\n topic.publishMessage(pub);\n }\n });\n })\n .catch((err) => {\n this.props.onError(err.message, 'err');\n const {formatMessage} = this.props.intl;\n this.setState({\n title: formatMessage(messages.not_found),\n avatar: null,\n readOnly: true,\n writeOnly: true,\n fetchingMessages: false,\n messages: [],\n onlineSubs: [],\n typingIndicator: false,\n imagePreview: null\n });\n });\n }\n }\n\n leave(oldTopicName) {\n if (!oldTopicName) {\n return;\n }\n let 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 });\n }\n }\n\n handleScrollReference(node) {\n if (node) {\n node.addEventListener('scroll', this.fetchMoreMessages);\n this.messagesScroller = node;\n }\n }\n\n // Get older messages\n fetchMoreMessages(event) {\n if (event.target.scrollTop <= 0) {\n let newState = {scrollPosition: event.target.scrollHeight - event.target.scrollTop};\n this.setState((prevState, props) => {\n if (!prevState.fetchingMessages) {\n var topic = this.props.tinode.getTopic(this.state.topic);\n if (topic && topic.isSubscribed() && topic.msgHasMoreMessages()) {\n newState.fetchingMessages = true;\n topic.getMessagesPage(MESSAGES_PAGE).catch((err) => {\n this.setState({fetchingMessages: false});\n this.props.onError(err.message, 'err');\n });\n }\n }\n return newState;\n });\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 if (desc.acs) {\n this.setState({\n readOnly: !desc.acs.isWriter(),\n writeOnly: !desc.acs.isReader()\n });\n }\n }\n\n handleSubsUpdated() {\n if (this.state.topic) {\n var subs = [];\n var 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 this.setState({onlineSubs: subs});\n }\n }\n\n handleNewMessage(msg) {\n // Regenerate messages list\n var topic = this.props.tinode.getTopic(this.state.topic);\n var newState = {messages: []};\n topic.messages(function(m) {\n if (!m.deleted) {\n newState.messages = newState.messages.concat(m);\n }\n });\n\n // msg could be null if one or more messages were deleted.\n if (msg && !msg.deleted) {\n // If the message is added to the end of the message list,\n // scroll to the bottom.\n if (topic.isNewMessage(msg.seq)) {\n newState.scrollPosition = 0;\n }\n\n // Aknowledge all messages, including own messages.\n let status = topic.msgStatus(msg);\n if (status >= Tinode.MESSAGE_STATUS_SENT) {\n this.props.readTimerHandler(() => {\n topic.noteRead(msg.seq);\n });\n }\n this.props.onData(msg);\n }\n\n this.setState(newState);\n }\n\n handleAllMessagesReceived(count) {\n this.setState({fetchingMessages: false});\n }\n\n handleInfoReceipt(info) {\n switch (info.what) {\n case 'kp': {\n clearTimeout(this.keyPressTimer);\n var instance = this;\n this.keyPressTimer = setTimeout(function() {\n instance.setState({typingIndicator: false});\n }, 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.log(\"Other change in topic: \", info.what);\n }\n }\n\n handleImagePreview(content) {\n this.setState({ imagePreview: content });\n }\n\n handleCloseImagePreview() {\n this.setState({ imagePreview: null });\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 handleShowContextMenuMessage(params) {\n params.topicName = this.state.topic;\n var menuItems = ['message_delete'];\n var topic = this.props.tinode.getTopic(params.topicName);\n if (topic) {\n var 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 handleBackNavigation() {\n this.props.onHideMessagesView();\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n\n let component;\n\n if (this.state.topic) {\n let messageNodes = [];\n let topic = this.props.tinode.getTopic(this.state.topic);\n let groupTopic = topic.getType() == 'grp';\n let previousFrom = null;\n let chatBoxClass = null;\n for (let i=0; i \n );\n }\n\n let lastSeen = null;\n let cont = this.props.tinode.getMeTopic().getContact(this.state.topic);\n if (cont && Tinode.topicType(cont.topic) == 'p2p') {\n if (cont.online) {\n lastSeen = formatMessage(messages.online_now);\n } else if (cont.seen) {\n lastSeen = formatMessage(messages.last_seen) + \": \" + shortDateFormat(cont.seen.when);\n // TODO: also handle user agent in c.seen.ua\n }\n }\n let avatar = this.state.avatar || true;\n let online = this.props.online ? 'online' + (this.state.typingIndicator ? ' typing' : '') : 'offline';\n\n component = (\n \n
\n {this.props.displayMobile ?\n
\n arrow_back \n \n :\n null}\n
\n \n \n
\n
\n
{\n this.state.title ||\n \n }
\n
{lastSeen}
\n
\n {groupTopic ?\n
:\n
\n }\n
\n
\n {this.props.displayMobile ?\n
\n : null}\n
\n
\n
\n {this.state.writeOnly ?\n
\n :\n null\n }\n
\n
\n {this.state.imagePreview ?\n
: null}\n
\n );\n } else {\n component = (\n \n );\n }\n return component;\n }\n};\n\nexport default injectIntl(MessagesView);\n","import React from 'react';\n\nexport default class MenuContacts extends React.PureComponent {\n render() {\n return (\n \n );\n }\n};\n","import React from 'react';\n\nexport default class MenuStart extends React.PureComponent {\n render() {\n return (\n \n );\n }\n};\n","import React from 'react';\n\nimport LetterTile from './letter-tile.jsx';\nimport MenuCancel from './menu-cancel.jsx';\nimport MenuContacts from './menu-contacts.jsx';\nimport MenuStart from './menu-start.jsx';\n\nexport default class SideNavbar extends React.PureComponent {\n render() {\n return (\n \n
\n \n
\n
{this.props.title}
\n {this.props.state === 'login' ?\n
:\n this.props.state === 'contacts' ?\n
:\n null}\n {this.props.onCancel ?\n
: null}\n
\n );\n }\n};\n","/* ContactsView holds all contacts-related stuff */\nimport React from 'react';\nimport { FormattedHTMLMessage } from 'react-intl';\n\nimport ContactList from '../widgets/contact-list.jsx';\n\nimport { updateFavicon } from '../lib/utils.js';\n\nexport default class ContactsView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = ContactsView.getDerivedStateFromProps(props, {});\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n let contacts = [];\n let unreadThreads = 0;\n nextProps.chatList.map((c) => {\n unreadThreads += c.unread > 0 ? 1 : 0;\n contacts.push(c);\n });\n contacts.sort(function(a, b){\n return (b.touched || 0) - (a.touched || 0);\n });\n\n updateFavicon(unreadThreads);\n\n return {contactList: contacts};\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","// 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 let 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 let 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","// Account registration.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport AvatarUpload from '../widgets/avatar-upload.jsx';\nimport CheckBox from '../widgets/checkbox.jsx';\nimport VisiblePassword from '../widgets/visible-password.jsx';\n\nimport LocalStorageUtil from '../lib/local-storage.js';\nimport { vcard } from '../lib/utils.js';\n\nexport default class CreateAccountView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n login: '',\n password: '',\n email: '',\n fn: '', // full/formatted name\n imageDataUrl: null,\n errorCleared: false,\n saveToken: LocalStorageUtil.getObject('keep-logged-in')\n };\n\n this.handleLoginChange = this.handleLoginChange.bind(this);\n this.handlePasswordChange = this.handlePasswordChange.bind(this);\n this.handleEmailChange = this.handleEmailChange.bind(this);\n this.handleFnChange = this.handleFnChange.bind(this);\n this.handleImageChanged = this.handleImageChanged.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(password) {\n this.setState({password: password});\n }\n\n handleEmailChange(e) {\n this.setState({email: e.target.value})\n }\n\n handleFnChange(e) {\n this.setState({fn: e.target.value});\n }\n\n handleImageChanged(img) {\n this.setState({imageDataUrl: img});\n }\n\n handleToggleSaveToken() {\n LocalStorageUtil.setObject('keep-logged-in', !this.state.saveToken);\n this.setState({saveToken: !this.state.saveToken});\n }\n\n handleSubmit(e) {\n e.preventDefault();\n // TODO: check email for validity\n this.setState({errorCleared: false});\n this.props.onCreateAccount(\n this.state.login.trim(),\n this.state.password.trim(),\n vcard(this.state.fn, this.state.imageDataUrl),\n {'meth': 'email', 'val': this.state.email});\n }\n\n render() {\n let submitClasses = 'blue';\n if (this.props.disabled) {\n submitClasses += ' disabled';\n }\n\n return (\n \n );\n }\n};\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport AvatarUpload from '../widgets/avatar-upload.jsx';\nimport CheckBox from '../widgets/checkbox.jsx';\nimport InPlaceEdit from '../widgets/in-place-edit.jsx';\nimport PermissionsEditor from '../widgets/permissions-editor.jsx';\nimport TagManager from '../widgets/tag-manager.jsx';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\nexport default class EditAccountView extends React.Component {\n constructor(props) {\n super(props);\n\n let me = this.props.tinode.getMeTopic();\n let defacs = me.getDefaultAccess();\n let fnd = this.props.tinode.getFndTopic();\n this.state = {\n fullName: me.public ? me.public.fn : undefined,\n avatar: makeImageUrl(me.public ? me.public.photo : null),\n auth: defacs ? defacs.auth : null,\n anon: defacs ? defacs.anon : null,\n tags: fnd.tags(),\n showPermissionEditorFor: undefined,\n previousOnTags: fnd.onTagsUpdated\n };\n\n this.tnNewTags = this.tnNewTags.bind(this);\n this.handleFullNameUpdate = this.handleFullNameUpdate.bind(this);\n this.handlePasswordUpdate = this.handlePasswordUpdate.bind(this);\n this.handleImageChanged = this.handleImageChanged.bind(this);\n this.handleCheckboxClick = this.handleCheckboxClick.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.handleTagsUpdated = this.handleTagsUpdated.bind(this);\n }\n\n componentDidMount() {\n let fnd = this.props.tinode.getFndTopic();\n fnd.onTagsUpdated = this.tnNewTags;\n if (!fnd.isSubscribed()) {\n fnd.subscribe(fnd.startMetaQuery().withLaterDesc().withTags().build()).catch((err) => {\n this.props.onError(err.message, 'err');\n });\n }\n }\n\n componentWillUnmount() {\n var fnd = this.props.tinode.getFndTopic();\n fnd.onTagsUpdated = this.state.previousOnTags;\n }\n\n tnNewTags(tags) {\n this.setState({tags: tags});\n }\n\n handleFullNameUpdate(fn) {\n this.setState({fullName: fn});\n this.props.onUpdateAccount(undefined, vcard(fn, this.state.avatar));\n }\n\n handlePasswordUpdate(pwd) {\n this.setState({password: pwd});\n this.props.onUpdateAccount(pwd);\n }\n\n handleImageChanged(img) {\n this.setState({avatar: img});\n this.props.onUpdateAccount(undefined, vcard(this.state.fullName, img));\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 }\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.onUpdateAccount(undefined, undefined, defacs);\n\n let newState = {showPermissionEditorFor: undefined};\n newState[this.state.showPermissionEditorFor] = perm;\n this.setState(newState);\n }\n\n handleTagsUpdated(tags) {\n // Check if tags have actually changed.\n if (arrayEqual(this.state.tags.slice(0), tags.slice(0))) {\n return;\n }\n this.props.onUpdateTags(tags);\n }\n\n render() {\n var tags = [];\n this.state.tags.map(function(tag) {\n tags.push({tag} );\n });\n if (tags.length == 0) {\n tags = ;\n }\n return (\n {this.state.showPermissionEditorFor ?\n \n :\n \n
\n
\n
\n \n
\n
{\n (full_name_placeholder) => \n }
\n
\n \n
\n
\n {\n (password_unchanged) => \n } \n
\n
\n
\n
\n
\n
\n
\n \n {this.props.myUserId} \n
\n
\n \n \n \n
\n
\n
Auth: {this.state.auth}
\n
Anon: {this.state.anon}
\n
\n
\n
\n
\n \n \n \n \n
\n
\n \n {this.props.desktopAlertsEnabled ?\n \n :\n \n }\n \n \n
\n
\n
{\n (title_tag_manager) => \n } \n
\n
\n
\n } \n );\n }\n};\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\nimport LocalStorageUtil from '../lib/local-storage.js';\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: LocalStorageUtil.getObject('keep-logged-in')\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 LocalStorageUtil.setObject('keep-logged-in', !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 var submitClasses = 'blue';\n if (this.props.disabled) {\n submitClasses += ' disabled';\n }\n\n return (\n \n );\n }\n};\n/* END Login */\n","import React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nconst messages = defineMessages({\n invalid_id: {\n id: 'error_invalid_id',\n defaultMessage: 'Invalid ID',\n description: 'Error message'\n }\n});\n\nclass NewTopicById extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n groupId: '',\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleKeyPress = this.handleKeyPress.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n handleChange(e) {\n this.setState({groupId: e.target.value});\n }\n\n handleKeyPress(e) {\n if (e.key === 'Enter') {\n this.handleSubmit(e);\n }\n }\n\n handleSubmit(e) {\n e.preventDefault();\n if (this.state.groupId) {\n var name = this.state.groupId.trim();\n if (name.length > 3 && (name.substr(0, 3) == 'usr' || name.substr(0, 3) == 'grp')) {\n this.props.onSubmit(name);\n } else {\n this.props.onError(this.props.intl.formatMessage(messages.invalid_id), 'err');\n }\n }\n }\n\n render() {\n return (\n \n
\n {\n (prompt) => \n } \n
\n
\n \n \n \n
\n
\n );\n }\n};\n\nexport default injectIntl(NewTopicById);\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport AvatarUpload from './avatar-upload.jsx';\nimport TagManager from './tag-manager.jsx';\n\nexport default class NewTopicGroup extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n fn: '', // full/formatted name\n private: '',\n imageDataUrl: null,\n tags: []\n };\n\n this.handleFnChange = this.handleFnChange.bind(this);\n this.handlePrivateChange = this.handlePrivateChange.bind(this);\n this.handleImageChanged = this.handleImageChanged.bind(this);\n this.handleTagsChanged = this.handleTagsChanged.bind(this);\n this.handleTagsChanged = this.handleTagsChanged.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n handleFnChange(e) {\n this.setState({fn: e.target.value});\n }\n\n handlePrivateChange(e) {\n this.setState({private: e.target.value});\n }\n\n handleImageChanged(img) {\n this.setState({imageDataUrl: img});\n }\n\n handleTagsChanged(tags) {\n this.setState({tags: tags});\n }\n\n handleSubmit(e) {\n e.preventDefault();\n if (this.state.fn && this.state.fn.trim()) {\n this.props.onSubmit(this.state.fn.trim(),\n this.state.imageDataUrl, this.state.private.trim(),\n this.state.tags);\n }\n }\n\n render() {\n var submitClasses = 'blue';\n if (this.props.disabled) {\n submitClasses += ' disabled';\n }\n return (\n \n );\n }\n};\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport Tinode from 'tinode-sdk';\n\nexport default class SearchContacts extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n edited: false,\n search: ''\n };\n\n this.handleSearchChange = this.handleSearchChange.bind(this);\n this.handleSearch = this.handleSearch.bind(this);\n this.handleClear = this.handleClear.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n }\n\n componentWillUnmount() {\n if (this.state.edited) {\n this.setState({search: '', edited: false});\n this.props.onSearchContacts(Tinode.DEL_CHAR);\n }\n }\n\n handleSearchChange(e) {\n this.setState({search: e.target.value});\n }\n\n handleSearch(e) {\n e.preventDefault();\n var query = this.state.search.trim();\n this.setState({edited: (query.length > 0)});\n this.props.onSearchContacts(query.length > 0 ? query : Tinode.DEL_CHAR);\n }\n\n handleClear() {\n if (this.state.edited) {\n this.props.onSearchContacts(Tinode.DEL_CHAR);\n }\n this.setState({search: '', edited: false});\n }\n\n handleKeyDown(e) {\n if (e.key === 'Enter') {\n this.handleSearch(e);\n } else if (e.key === 'Escape') {\n this.handleClear();\n }\n }\n\n render() {\n return (\n \n
\n
search \n
{\n (search_placeholder) => \n } \n
\n close \n \n
\n
\n );\n }\n};\n","// Utility class for hash navigation.\n\n// Parse hash as in http://www.example.com/path#hash as if it were\n// path and arguments.\nexport default class HashNavigation {\n static parseUrlHash(hash) {\n // Split path from args, path -> parts[0], args->path[1]\n let parts = hash.split('?', 2);\n let params = {};\n let path = [];\n if (parts[0]) {\n path = parts[0].substr(1).split('/');\n }\n if (parts[1]) {\n parts[1].split('&').forEach(function(part) {\n let item = part.split('=');\n if (item[0]) {\n params[decodeURIComponent(item[0])] = decodeURIComponent(item[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 var url = path.join('/');\n var args = [];\n for (var key in params) {\n if (params.hasOwnProperty(key)) {\n args.push(key + '=' + 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 var parsed = this.parseUrlHash(hash);\n parsed.params[key] = value;\n return this.composeUrlHash(parsed.path, parsed.params);\n }\n\n static removeUrlParam(hash, key) {\n var parsed = this.parseUrlHash(hash);\n delete parsed.params[key];\n return this.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlSidePanel(hash, sidepanel) {\n var parsed = this.parseUrlHash(hash);\n parsed.path[0] = sidepanel;\n return this.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlTopic(hash, topic) {\n var parsed = this.parseUrlHash(hash);\n parsed.path[1] = topic;\n // Close InfoView on topic change.\n delete parsed.params.info;\n return this.composeUrlHash(parsed.path, parsed.params);\n }\n}\n","// Create new topic and invite users or send an invite.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\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';\n\nexport default class NewTopicView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n tabSelected: 'p2p',\n contactList: props.searchResults\n };\n\n this.handleTabClick = this.handleTabClick.bind(this);\n this.handleContactSelected = this.handleContactSelected.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 static getDerivedStateFromProps(nextProps, prevState) {\n return {\n contactList: nextProps.searchResults\n };\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 handleContactSelected(sel) {\n if (this.state.tabSelected === 'p2p') {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'tab'));\n this.props.onCreateTopic(sel, undefined);\n }\n }\n\n handleNewGroupSubmit(name, dataUrl, priv, tags) {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'tab'));\n this.props.onCreateTopic(undefined, vcard(name, dataUrl), priv, tags);\n }\n\n handleGroupByID(topicName) {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'tab'));\n this.props.onCreateTopic(topicName);\n }\n\n render() {\n return (\n \n
\n {this.state.tabSelected === 'grp' ?\n
:\n this.state.tabSelected === 'byid' ?\n
:\n
\n \n {\n (search_for_contacts) => \n } \n
}\n
\n );\n }\n};\n","// A password reset form.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport VisiblePassword from '../widgets/visible-password.jsx';\n\nimport HashNavigation from '../lib/navigation.js';\n\nexport default class PasswordResetView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n email: '',\n password: ''\n };\n\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleEmailChange = this.handleEmailChange.bind(this);\n this.handlePasswordChange = this.handlePasswordChange.bind(this);\n }\n\n componentDidMount() {\n let parsed = HashNavigation.parseUrlHash(window.location.hash);\n this.setState({token: parsed.params.token, scheme: parsed.params.scheme});\n }\n\n handleSubmit(e) {\n e.preventDefault();\n if (this.state.token) {\n this.props.onReset(this.state.scheme, this.state.password.trim(), this.state.token);\n } else {\n this.props.onRequest('email', this.state.email.trim());\n }\n }\n\n handleEmailChange(e) {\n this.setState({email: e.target.value});\n }\n\n handlePasswordChange(e) {\n this.setState({password: e.target.value});\n }\n\n render() {\n let reset = (this.state.token && this.state.scheme);\n return (\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 }\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 render() {\n var hostOptions = [];\n for (let key in KNOWN_HOSTS) {\n let item = KNOWN_HOSTS[key];\n hostOptions.push(\n \n );\n }\n return (\n \n \n \n {hostOptions}\n \n
\n );\n }\n}\n","// Tinode config panel.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\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 };\n\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleTransportSelected = this.handleTransportSelected.bind(this);\n this.handleServerAddressChange = this.handleServerAddressChange.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 });\n }\n\n handleTransportSelected(e) {\n this.setState({transport: e.currentTarget.value});\n }\n\n handleServerAddressChange(name) {\n this.setState({serverAddress: name});\n this.props.onServerAddressChange(name);\n }\n\n render() {\n const names = {def: \"default\", ws: \"websocket\", lp: \"long polling\"};\n var transportOptions = [];\n var instance = this;\n ['def', 'ws', 'lp'].map(function(item) {\n var id = 'transport-' + item;\n var name = names[item];\n transportOptions.push(\n \n \n {name} \n \n );\n });\n\n return (\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 };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleKeyPress = this.handleKeyPress.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n handleChange(e) {\n this.setState({code: e.target.value});\n }\n\n handleKeyPress(e) {\n if (e.key === 'Enter') {\n this.handleSubmit(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());\n }\n }\n\n render() {\n const { formatMessage } = this.props.intl;\n const methods = {'email': formatMessage(messages.email), 'tel': formatMessage(messages.phone)};\n let method = methods[this.props.credMethod] || this.props.credMethod;\n return (\n \n
\n \n \n \n
\n
\n {\n (numbers_only) => \n } \n
\n
\n \n \n \n
\n
\n );\n }\n};\n\nexport default injectIntl(ValidationView);\n","import React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport SideNavbar from '../widgets/side-navbar.jsx';\nimport ErrorPanel from '../widgets/error-panel.jsx';\n\nimport ContactsView from './contacts-view.jsx';\nimport CreateAccountView from './create-account-view.jsx';\nimport EditAccountView from './edit-account-view.jsx';\nimport LoginView from './login-view.jsx';\nimport NewTopicView from './new-topic-view.jsx';\nimport PasswordResetView from './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_edit_account',\n description: 'Sidepanel title for EditAccountView.',\n defaultMessage: 'Edit Account'\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});\n\nclass SidepanelView extends React.Component {\n constructor(props) {\n super(props);\n\n this.handleLoginRequested = this.handleLoginRequested.bind(this);\n }\n\n handleLoginRequested(login, password) {\n this.props.onLoginRequest(login, password);\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;\n if (view == 'contacts') {\n title = this.props.title;\n avatar = this.props.avatar ? this.props.avatar : true;\n } else {\n title = formatMessage(messages[view]);\n avatar = false;\n }\n\n let onCancel;\n if (view != 'login') {\n onCancel = this.props.onCancel;\n }\n\n return (\n \n
\n\n
\n\n {view === 'login' ?\n
:\n\n view === 'register' ?\n
:\n\n view === 'settings' ?\n
:\n\n view === 'edit' ?\n
:\n\n view === 'contacts' ?\n
:\n\n view === 'newtpk' ?\n
:\n\n view === 'cred' ?\n
:\n\n view === 'reset' ?\n
:\n null}\n
\n );\n }\n};\n\nexport default injectIntl(SidepanelView);\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","// The top-level class to hold all functionality together.\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport * as firebase from 'firebase/app';\nimport 'firebase/messaging';\n\nimport Tinode from 'tinode-sdk';\n\nimport ContextMenu from '../widgets/context-menu.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, MEDIA_BREAKPOINT, READ_DELAY, RECEIVED_DELAY } from '../config.js';\nimport { 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 { updateFavicon } from '../lib/utils.js';\n\n// Sound to play on message received.\nconst POP_SOUND = new Audio('audio/msg.mp3');\n\nconst messages = defineMessages({\n update_available: {\n id: 'update_available',\n defaultMessage: 'Update available. Reload .',\n description: 'Message shown when an app update is available.'\n }\n});\n\nclass TinodeWeb extends React.Component {\n constructor(props) {\n super(props);\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.handleAppVisibility = this.handleAppVisibility.bind(this);\n this.handleReadTimer = this.handleReadTimer.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.handleConnected = this.handleConnected.bind(this);\n this.doLogin = this.doLogin.bind(this);\n this.handleCredentialsRequest = this.handleCredentialsRequest.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.tnData = this.tnData.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.handleNewAccount = this.handleNewAccount.bind(this);\n this.handleNewAccountRequest = this.handleNewAccountRequest.bind(this);\n this.handleUpdateAccountRequest = this.handleUpdateAccountRequest.bind(this);\n this.handleUpdateAccountTagsRequest = this.handleUpdateAccountTagsRequest.bind(this);\n this.handleSettings = this.handleSettings.bind(this);\n this.handleGlobalSettings = this.handleGlobalSettings.bind(this);\n this.handleToggleMessageSounds = this.handleToggleMessageSounds.bind(this);\n this.initDesktopAlerts = this.initDesktopAlerts.bind(this);\n this.togglePushToken = this.togglePushToken.bind(this);\n this.requestPushToken = this.requestPushToken.bind(this);\n this.handleSidepanelCancel = this.handleSidepanelCancel.bind(this);\n this.handleNewTopic = this.handleNewTopic.bind(this);\n this.handleNewTopicRequest = this.handleNewTopicRequest.bind(this);\n this.handleNewTopicCreated = this.handleNewTopicCreated.bind(this);\n this.handleTopicUpdateRequest = this.handleTopicUpdateRequest.bind(this);\n this.handleChangePermissions = this.handleChangePermissions.bind(this);\n this.handleTagsUpdated = this.handleTagsUpdated.bind(this);\n this.handleLogout = this.handleLogout.bind(this);\n this.handleLeaveUnsubRequest = this.handleLeaveUnsubRequest.bind(this);\n this.handleDialogCancel = this.handleDialogCancel.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.handleShowInfoView = this.handleShowInfoView.bind(this);\n this.handleHideInfoView = this.handleHideInfoView.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 }\n\n getBlankState() {\n let settings = LocalStorageUtil.getObject(\"settings\") || {};\n\n return {\n connected: false,\n transport: settings.transport || null,\n serverAddress: settings.serverAddress || detectServerAddress(),\n serverVersion: \"no connection\",\n // \"On\" is the default, so saving the \"off\" state.\n messageSounds: !settings.messageSoundsOff,\n desktopAlerts: settings.desktopAlerts,\n desktopAlertsEnabled: (isSecureConnection() || isLocalHost()) &&\n (typeof firebase != 'undefined') && (typeof navigator != 'undefined') &&\n (typeof FIREBASE_INIT != 'undefined'),\n firebaseToken: LocalStorageUtil.getObject(\"firebase-token\"),\n\n errorText: '',\n errorLevel: null,\n\n sidePanelSelected: 'login',\n sidePanelTitle: null,\n sidePanelAvatar: null,\n dialogSelected: null,\n contextMenuVisible: false,\n login: '',\n password: '',\n myUserId: null,\n liveConnection: navigator.onLine,\n topicSelected: '',\n topicSelectedOnline: false,\n topicSelectedAcs: null,\n newGroupTopicParams: null,\n loginDisabled: false,\n displayMobile: (window.innerWidth <= MEDIA_BREAKPOINT),\n showInfoPanel: false,\n mobilePanel: 'sidepanel',\n\n contextMenuVisible: false,\n contextMenuBounds: null,\n contextMenuClickAt: null,\n contextMenuParams: null,\n contextMenuItems: [],\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 credMethod: undefined,\n credCode: undefined\n };\n }\n\n componentDidMount() {\n window.addEventListener('resize', this.handleResize);\n window.addEventListener('online', (e) => { this.handleOnline(true); });\n window.addEventListener('offline', (e) => { this.handleOnline(false); });\n window.addEventListener('hashchange', this.handleHashRoute);\n // Window/tab visible or invisible for pausing timers.\n document.addEventListener('visibilitychange', this.handleVisibilityEvent);\n\n this.setState({viewportWidth: document.documentElement.clientWidth});\n\n this.tinode = TinodeWeb.tnSetup(this.state.serverAddress, this.state.transport);\n this.tinode.onConnect = this.handleConnected;\n this.tinode.onDisconnect = this.handleDisconnect;\n\n // Initialize desktop alerts.\n if (this.state.desktopAlertsEnabled) {\n try {\n this.fbPush = firebase.initializeApp(FIREBASE_INIT, APP_NAME).messaging();\n this.fbPush.usePublicVapidKey(FIREBASE_INIT.messagingVapidKey);\n navigator.serviceWorker.register('/service-worker.js').then((reg) => {\n this.checkForAppUpdate(reg);\n this.fbPush.useServiceWorker(reg);\n this.initDesktopAlerts();\n if (this.state.desktopAlerts) {\n if (!this.state.firebaseToken) {\n this.togglePushToken(true);\n } else {\n this.tinode.setDeviceToken(this.state.firebaseToken);\n }\n }\n }).catch((err) => {\n // registration failed :(\n console.log(\"Failed to register service worker:\", err);\n });\n } catch (err) {\n this.handleError(\"Failed to initialize push notifications\", 'err');\n console.log(\"Failed to initialize push notifications\", err);\n this.setState({desktopAlertsEnabled: false});\n }\n }\n\n let token = LocalStorageUtil.getObject('keep-logged-in') ?\n LocalStorageUtil.getObject('auth-token') : undefined;\n\n let parsedNav = HashNavigation.parseUrlHash(window.location.hash);\n if (token) {\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 delete parsedNav.params.info;\n delete parsedNav.params.tab;\n parsedNav.path[0] = '';\n HashNavigation.navigateTo(HashNavigation.composeUrlHash(parsedNav.path, parsedNav.params));\n } else if (!parsedNav.params.token) {\n HashNavigation.navigateTo('');\n }\n\n this.readTimer = null;\n this.readTimerCallback = null;\n\n this.handleHashRoute();\n }\n\n componentWillUnmount() {\n window.removeEventListener('resize', this.handleResize);\n window.removeEventListener('hashchange', this.handleHashRoute);\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, transport) {\n let tinode = new Tinode(APP_NAME, serverAddress, API_KEY, transport, isSecureConnection());\n tinode.enableLogging(true, true);\n return tinode;\n }\n\n handleResize() {\n var mobile = document.documentElement.clientWidth <= MEDIA_BREAKPOINT;\n this.setState({viewportWidth: document.documentElement.clientWidth});\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 const {formatHTMLMessage} = this.props.intl;\n reg.onupdatefound = () => {\n const installingWorker = reg.installing;\n installingWorker.onstatechange = () => {\n if (installingWorker.state == 'installed' && navigator.serviceWorker.controller) {\n this.handleError(formatHTMLMessage(messages.update_available), 'info');\n }\n }\n }\n }\n\n // Handle for hashchange event: display appropriate panels.\n handleHashRoute() {\n var hash = HashNavigation.parseUrlHash(window.location.hash);\n if (hash.path && hash.path.length > 0) {\n // Left-side panel selector.\n if (['register','settings','edit','cred','reset','newtpk','contacts',''].includes(hash.path[0])) {\n this.setState({sidePanelSelected: hash.path[0]});\n } else {\n console.log(\"Unknown sidepanel view\", hash.path[0]);\n }\n\n // Topic for MessagesView selector.\n if (hash.path.length > 1 && hash.path[1] != this.state.topicSelected) {\n this.setState({\n topicSelected: Tinode.topicType(hash.path[1]) ? hash.path[1] : null\n });\n }\n } else {\n // Empty hashpath\n this.setState({sidePanelSelected: ''});\n }\n\n // Save validation credentials, if available.\n if (hash.params.method) {\n this.setState({ credMethod: hash.params.method });\n }\n if (hash.params.code) {\n this.setState({ credCode: hash.params.code });\n }\n\n // Additional parameters of panels.\n this.setState({\n showInfoPanel: hash.params.info,\n newTopicTabSelected: hash.params.tab\n });\n }\n\n handleOnline(online) {\n var newState = {liveConnection: online};\n if (online) {\n this.handleError('', null);\n } else {\n this.handleError(\"No connection\", 'warn');\n }\n this.setState({liveConnection: online});\n }\n\n // Handling read notifications here to be able to pause\n // them then the window/tab is not visible.\n handleAppVisibility(visible, callback) {\n clearTimeout(this.readTimer);\n this.readTimerCallback = callback;\n if (visible && callback) {\n this.readTimer = setTimeout(callback, READ_DELAY);\n } else {\n this.readTimer = null;\n }\n }\n\n handleReadTimer(callback) {\n this.handleAppVisibility(!document.hidden, callback);\n }\n\n handleVisibilityEvent() {\n this.handleAppVisibility(!document.hidden, this.readTimerCallback);\n }\n\n handleError(err, level) {\n this.setState({errorText: err, errorLevel: level});\n }\n\n // User clicked Login button in the side panel.\n handleLoginRequest(login, password) {\n this.setState({loginDisabled: true, login: login, password: password});\n this.handleError('', null);\n\n if (this.tinode.isConnected()) {\n this.doLogin(login, password, {meth: this.state.credMethod, resp: this.state.credCode});\n } else {\n this.tinode.connect().catch((err) => {\n // Socket error\n this.setState({loginDisabled: false});\n this.handleError(err.message, 'err');\n });\n }\n }\n\n // Connection succeeded.\n handleConnected() {\n var params = this.tinode.getServerInfo();\n this.setState({\n serverVersion: params.ver + ' ' + (params.build ? params.build : 'none') + '; '\n });\n this.doLogin(this.state.login, this.state.password, {meth: this.state.credMethod, resp: this.state.credCode});\n }\n\n doLogin(login, password, cred) {\n if (this.tinode.isAuthenticated()) {\n // Already logged in. Go to default screen.\n HashNavigation.navigateTo('');\n return;\n }\n // Sanitize and package credentail.\n cred = Tinode.credential(cred);\n // Try to login with login/password. If they are not available, try token. If no token, ask for login/password.\n let promise = null;\n let token = this.tinode.getAuthToken();\n if (login && password) {\n this.setState({password: null});\n promise = this.tinode.loginBasic(login, password, cred);\n } else if (token) {\n promise = this.tinode.loginToken(token.token, cred);\n }\n\n if (promise) {\n promise.then((ctrl) => {\n if (ctrl.code >= 300 && ctrl.text === 'validate credentials') {\n if (cred) {\n this.handleError(\"Code does not match\", 'warn');\n }\n this.handleCredentialsRequest(ctrl.params);\n } else {\n this.handleLoginSuccessful();\n }\n }).catch((err) => {\n // Login failed, report error.\n this.setState({loginDisabled: false, credMethod: undefined, credCode: undefined});\n this.handleError(err.message, 'err');\n localStorage.removeItem('auth-token');\n HashNavigation.navigateTo('');\n });\n } else {\n // No login credentials provided.\n // Make sure we are on the login page.\n HashNavigation.navigateTo('');\n this.setState({loginDisabled: false});\n }\n }\n\n handleCredentialsRequest(params) {\n var parsed = HashNavigation.parseUrlHash(window.location.hash);\n parsed.path[0] = 'cred';\n parsed.params['method'] = params.cred[0];\n HashNavigation.navigateTo(HashNavigation.composeUrlHash(parsed.path, parsed.params));\n }\n\n handleLoginSuccessful() {\n this.handleError('', null);\n\n // Refresh authentication token.\n if (LocalStorageUtil.getObject('keep-logged-in')) {\n LocalStorageUtil.setObject('auth-token', this.tinode.getAuthToken());\n }\n // Logged in fine, subscribe to 'me' attaching callbacks from the contacts view.\n var 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 myUserId: this.tinode.getCurrentUserID()\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 build()\n ).catch((err) => {\n localStorage.removeItem('auth-token');\n this.handleError(err.message, 'err');\n HashNavigation.navigateTo('');\n });\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash, 'contacts'));\n }\n\n handleDisconnect(err) {\n this.setState({\n connected: false,\n topicSelectedOnline: false,\n dialogSelected: null,\n errorText: err && err.message ? err.message : \"Disconnected\",\n errorLevel: err && err.message ? 'err' : 'warn',\n loginDisabled: false,\n contextMenuVisible: false,\n serverVersion: \"no connection\"\n });\n }\n\n tnMeMetaDesc(desc) {\n if (desc && desc.public) {\n this.setState({\n sidePanelTitle: desc.public.fn,\n sidePanelAvatar: makeImageUrl(desc.public.photo)\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 // New message received\n // Skip update if the topic is currently open, otherwise the badge will annoyingly flash.\n if (this.state.topicSelected != cont.topic) {\n if (this.state.messageSounds) {\n POP_SOUND.play();\n }\n this.resetContactList();\n } else if (document.hidden && this.state.messageSounds) {\n POP_SOUND.play();\n }\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 // messages deleted (hard or soft) -- update pill counter.\n } else {\n // TODO(gene): handle other types of notifications:\n // * ua -- user agent changes (maybe display a pictogram for mobile/desktop).\n // * upd -- topic 'public' updated, issue getMeta().\n console.log(\"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 kown contacts for GroupManager to use.\n static prepareSearchableContacts(chatList, foundContacts) {\n let 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.topicType(c.topic) == 'p2p') {\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 let newState = {\n chatList: []\n };\n this.tinode.getMeTopic().contacts((c) => {\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 // Merge search results and chat list.\n newState.searchableContacts = TinodeWeb.prepareSearchableContacts(newState.chatList, this.state.searchResults);\n this.setState(newState);\n }\n\n // Sending \"received\" notifications\n tnData(data) {\n let topic = this.tinode.getTopic(data.topic);\n if (topic.msgStatus(data) >= Tinode.MESSAGE_STATUS_SENT) {\n clearTimeout(this.receivedTimer);\n this.receivedTimer = setTimeout(() => {\n this.receivedTimer = undefined;\n topic.noteRecv(data.seq);\n }, RECEIVED_DELAY);\n }\n }\n\n /* Fnd topic: find contacts by tokens */\n tnInitFind() {\n let fnd = this.tinode.getFndTopic();\n if (fnd.isSubscribed()) {\n this.tnFndSubsUpdated();\n } else {\n fnd.onSubsUpdated = this.tnFndSubsUpdated;\n fnd.subscribe(fnd.startMetaQuery().withSub().withTags().build()).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n tnFndSubsUpdated() {\n let 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 var fnd = this.tinode.getFndTopic();\n fnd.setMeta({desc: {public: query}}).then((ctrl) => {\n return fnd.getMeta(fnd.startMetaQuery().withSub().build());\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n // User clicked on a contact in the side panel or deleted a contact.\n handleTopicSelected(topicName, unused_index, online, acs) {\n if (topicName) {\n this.setState({\n errorText: '',\n errorLevel: null,\n mobilePanel: 'topic-view',\n showInfoPanel: false\n });\n // Different contact selected.\n if (this.state.topicSelected != topicName) {\n this.setState({\n topicSelectedOnline: online,\n topicSelectedAcs: acs\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 showInfoPanel: false\n });\n if (this.state.topicSelected) {\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', null));\n }\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 handleSendMessage(msg, promise, uploader) {\n let topic = this.tinode.getTopic(this.state.topicSelected);\n\n msg = topic.createMessage(msg, false);\n // The uploader is used to show progress.\n msg._uploader = uploader;\n\n if (!topic.isSubscribed()) {\n if (!promise) {\n promise = Promise.resolve();\n }\n promise = promise.then(() => { return topic.subscribe(); });\n }\n\n if (promise) {\n promise = promise.catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n topic.publishDraft(msg, promise)\n .catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n // User chose a Sign Up menu item.\n handleNewAccount() {\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 this.tinode.connect(this.state.serverAddress)\n .then(() => {\n return this.tinode.createAccountBasic(login_, password_,\n {public: public_, tags: tags_, cred: Tinode.credential(cred_)});\n }).then((ctrl) => {\n if (ctrl.code >= 300 && ctrl.text == 'validate credentials') {\n this.handleCredentialsRequest(ctrl.params);\n } else {\n this.handleLoginSuccessful(this);\n }\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleUpdateAccountRequest(password, pub, defacs) {\n if (pub || defacs) {\n this.tinode.getMeTopic().setMeta({desc: {public: pub, defacs: defacs}}).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n if (password) {\n this.tinode.updateAccountBasic(null, this.tinode.getCurrentLogin(), password).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleUpdateAccountTagsRequest(tags) {\n this.tinode.getFndTopic().setMeta({tags: tags})\n .catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n // User chose Settings menu item.\n handleSettings() {\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 let serverAddress = settings.serverAddress || this.state.serverAddress;\n let transport = settings.transport || this.state.transport;\n if (this.tinode) {\n this.tinode.onDisconnect = undefined;\n this.tinode.disconnect();\n }\n this.tinode = TinodeWeb.tnSetup(serverAddress, transport);\n this.tinode.onConnect = this.handleConnected;\n this.tinode.onDisconnect = this.handleDisconnect;\n\n this.setState({\n serverAddress: serverAddress,\n transport: transport\n });\n LocalStorageUtil.setObject('settings', {\n serverAddress: serverAddress,\n transport: transport\n });\n\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash, ''));\n }\n\n // Initialize desktop alerts = push notifications.\n initDesktopAlerts() {\n // Google could not be bothered to mention that\n // onTokenRefresh is never called.\n this.fbPush.onTokenRefresh(() => {\n this.requestPushToken(true);\n });\n\n this.fbPush.onMessage((payload) => {\n // No need to do anything about it.\n // All the magic happends in the service worker.\n });\n }\n\n togglePushToken(enabled) {\n if (enabled) {\n if (!this.state.firebaseToken) {\n this.fbPush.requestPermission().then(() => {\n this.requestPushToken(true);\n }).catch((err) => {\n this.handleError(err.message, 'err');\n this.setState({desktopAlerts: false, firebaseToken: null});\n LocalStorageUtil.updateObject('settings', {desktopAlerts: false});\n console.log(\"Failed to get permission to notify.\", err);\n });\n } else {\n this.setState({desktopAlerts: true});\n LocalStorageUtil.updateObject('settings', {desktopAlerts: true});\n }\n } else if (this.state.firebaseToken) {\n this.fbPush.deleteToken(this.state.firebaseToken).catch((err) => {\n console.log(\"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 });\n } else {\n this.setState({desktopAlerts: false, firebaseToken: null});\n LocalStorageUtil.updateObject('settings', {desktopAlerts: false});\n }\n }\n\n requestPushToken(sendToServer) {\n this.fbPush.getToken().then((refreshedToken) => {\n if (refreshedToken != this.state.firebaseToken) {\n this.tinode.setDeviceToken(refreshedToken, sendToServer);\n LocalStorageUtil.setObject('firebase-token', refreshedToken);\n }\n this.setState({firebaseToken: refreshedToken, desktopAlerts: true});\n LocalStorageUtil.updateObject('settings', {desktopAlerts: true});\n }).catch((err) => {\n this.handleError(err.message, 'err');\n console.log(\"Failed to retrieve firebase token\", err);\n });\n }\n\n handleToggleMessageSounds(enabled) {\n this.setState({messageSounds: enabled});\n LocalStorageUtil.updateObject('settings', {\n messageSoundsOff: !enabled\n });\n }\n\n // User clicked Cancel button in Setting or Sign Up panel.\n handleSidepanelCancel() {\n var parsed = HashNavigation.parseUrlHash(window.location.hash);\n parsed.path[0] = this.state.myUserId ? 'contacts' : '';\n if (parsed.params) {\n delete parsed.params.code;\n delete parsed.params.method;\n delete parsed.params.tab;\n }\n HashNavigation.navigateTo(HashNavigation.composeUrlHash(parsed.path, parsed.params));\n this.setState({errorText: '', errorLevel: null});\n }\n\n // User clicked a (+) menu item.\n handleNewTopic() {\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash, 'newtpk'));\n }\n\n // Request to start a new topic. New P2P topic requires peer's name.\n handleNewTopicRequest(peerName, pub, priv, tags) {\n var topicName = peerName || this.tinode.newGroupTopicName();\n if (!peerName) {\n this.setState(\n {newGroupTopicParams: {desc: {public: pub, private: {comment: priv}}, tags: tags}},\n () => {this.handleTopicSelected(topicName)}\n );\n } else {\n this.handleTopicSelected(topicName);\n }\n }\n\n // New topic was creted, here is the new topic name.\n handleNewTopicCreated(oldName, newName) {\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 this.setState({topicSelected: newName}, () => {\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', newName));\n });\n }\n }\n\n handleTopicUpdateRequest(topicName, pub, priv, permissions) {\n var topic = this.tinode.getTopic(topicName);\n if (topic) {\n var params = {};\n if (pub) {\n params.public = pub;\n }\n if (priv) {\n params.private = (priv === Tinode.DEL_CHAR) ?\n Tinode.DEL_CHAR : {comment: priv};\n }\n if (permissions) {\n params.defacs = permissions;\n }\n topic.setMeta({desc: params}).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleChangePermissions(topicName, mode, uid) {\n var topic = this.tinode.getTopic(topicName);\n if (topic) {\n var 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}}).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleTagsUpdated(topicName, tags) {\n var topic = this.tinode.getTopic(topicName);\n if (topic) {\n var instance = this;\n topic.setMeta({tags: tags}).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleLogout() {\n updateFavicon(0);\n localStorage.removeItem('auth-token');\n if (this.tinode) {\n this.tinode.onDisconnect = undefined;\n this.tinode.disconnect();\n }\n this.setState(this.getBlankState());\n this.tinode = TinodeWeb.tnSetup(this.state.serverAddress, this.state.transport);\n this.tinode.onConnect = this.handleConnected;\n this.tinode.onDisconnect = this.handleDisconnect;\n HashNavigation.navigateTo('');\n }\n\n handleLeaveUnsubRequest(topicName) {\n var topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n topic.leave(true).then((ctrl) => {\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 handleDialogCancel() {\n this.setState({dialogSelected: null});\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: ReactDOM.findDOMNode(this).getBoundingClientRect()\n });\n }\n\n defaultTopicContextMenu(topicName) {\n const topic = this.tinode.getTopic(topicName);\n const {formatMessage} = this.props.intl;\n\n let muted = false, blocked = false, subscribed = false, deleter = false;\n if (topic) {\n if (topic.isSubscribed()) {\n subscribed = true;\n\n let acs = topic.getAccessMode();\n muted = acs && acs.isMuted();\n blocked = acs && !acs.isJoiner();\n deleter = acs && acs.isDeleter();\n }\n }\n\n return [\n subscribed ? {title: formatMessage({id: 'menu_item_info'}), handler: this.handleShowInfoView} : null,\n subscribed ? 'messages_clear' : null,\n subscribed && deleter ? 'messages_clear_hard' : null,\n subscribed ? (muted ? 'topic_unmute' : 'topic_mute') : null,\n subscribed ? (blocked ? 'topic_unblock' : 'topic_block') : null,\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 handleShowInfoView() {\n HashNavigation.navigateTo(HashNavigation.addUrlParam(window.location.hash, 'info', true));\n this.setState({showInfoPanel: true});\n }\n\n handleHideInfoView() {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'info'));\n this.setState({showInfoPanel: false});\n }\n\n handleMemberUpdateRequest(topicName, added, removed) {\n if (!topicName) {\n return;\n }\n\n var topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n if (added && added.length > 0) {\n added.map((uid) => {\n topic.invite(uid, null).catch((err) => {\n this.handleError(err.message, 'err');\n });\n });\n }\n\n if (removed && removed.length > 0) {\n removed.map((uid) => {\n topic.delSubscription(uid).catch((err) => {\n this.handleError(err.message, 'err');\n });\n });\n }\n }\n\n handleValidateCredentialsRequest(cred, code) {\n this.setState({credMethod: cred, credCode: code});\n this.doLogin(null, null, {meth: cred, resp: code});\n }\n\n handlePasswordResetRequest(method, value) {\n // If already connected, connnect() will return a resolved promise.\n this.tinode.connect()\n .then(() => {\n return this.tinode.requestResetAuthSecret('basic', method, value)\n })\n .catch((err) => {\n // Socket error\n this.handleError(err.message, 'err');\n });\n }\n\n handleResetPassword(scheme, newPassword, token) {\n token = base64ReEncode(token);\n if (!token) {\n this.handleError(\"Invalid security token\", 'err');\n } else {\n this.tinode.connect()\n .then(() => {\n return this.tinode.updateAccountBasic(null, null, newPassword, {token: token});\n })\n .catch((err) => {\n // Socket error\n this.handleError(err.message, 'err');\n });\n }\n }\n\n render() {\n return (\n \n {this.state.contextMenuVisible ?\n \n :\n null\n }\n\n \n\n \n\n {this.state.showInfoPanel ?\n \n :\n null\n }\n
\n );\n }\n};\n\nexport default injectIntl(TinodeWeb);\n","// Put all packages together.\n// Used to generate umd/index.prod.js\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport { IntlProvider, addLocaleData } from 'react-intl';\nimport ruData from 'react-intl/locale-data/ru';\naddLocaleData(ruData);\nimport allMessages from './messages.json';\n\nimport TinodeWeb from './views/tinode-web.jsx';\n\nimport HashNavigation from './lib/navigation.js';\n\nconst {params} = HashNavigation.parseUrlHash(window.location.hash);\nconst language = (params && params.hl) ||\n (navigator.languages && navigator.languages[0]) ||\n navigator.language ||\n navigator.userLanguage;\n\nconst baseLanguage = language.toLowerCase().split(/[-_]+/)[0];\n\n// Try full locale, try locale without region code, fallback to 'en'\nconst messages =\n allMessages[language] ||\n allMessages[baseLanguage] ||\n allMessages.en;\n\nReactDOM.render(\n \n \n ,\n document.getElementById('mountPoint')\n);\n"],"sourceRoot":""}
\ No newline at end of file
diff --git a/webpack.config.js b/webpack.config.js
index 87da2060..0ee3d0b4 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -4,6 +4,7 @@ module.exports = config = {
entry: [
'./src/index.js',
],
+ devtool: 'source-map',
module: {
rules: [
{