57 Commits

Author SHA1 Message Date
Sharon Kennedy
40e968fcee 2.3.1 2020-12-15 10:24:42 -05:00
Sharon Kennedy
c45182a574 add default settings endpoint' 2020-12-15 10:24:20 -05:00
Sharon Kennedy
819d9b8ebb cleanup 2020-12-14 17:37:26 -05:00
Sharon Kennedy
4491b681c5 2.3.0 2020-11-28 15:03:17 -05:00
Sharon Kennedy
dcd7718f8f check schedule if using admin settings 2020-11-28 15:02:55 -05:00
Sharon Kennedy
c8c42e9086 2.2.2 2020-11-12 22:02:26 -05:00
Sharon Kennedy
004f88d5cd pass homeserver query param to get chatbox with settings 2020-11-12 22:01:51 -05:00
Sharon Kennedy
22c17d314d 2.2.1 2020-10-20 21:04:41 -04:00
Sharon Kennedy
2b3e46ad53 change anonymousDisplayName to displayName 2020-10-20 21:04:34 -04:00
Sharon Kennedy
43c5afd011 2.2.0 2020-10-20 19:30:52 -04:00
Sharon Kennedy
9432e4d86f optionally use settings from admin app 2020-10-20 19:30:15 -04:00
Sharon Kennedy
de4106c093 add option to fetch settings from external API 2020-10-20 18:38:38 -04:00
Sharon Kennedy
ee30b14cba 2.1.2 2020-10-16 13:43:23 -04:00
Sharon Kennedy
80c00149d2 main file should be chatbox 2020-10-16 13:43:15 -04:00
Sharon Kennedy
a2a48771e1 2.1.1 2020-10-15 12:25:08 -04:00
Sharon Kennedy
7bd6cf2466 package component 2020-10-15 12:24:59 -04:00
Sharon Kennedy
ac9247fecb 2.1.0 2020-10-15 11:40:38 -04:00
Sharon Kennedy
8439a1d100 export chatbox as react component 2020-10-15 11:40:12 -04:00
Sharon Kennedy
b709245b46 2.0.2 2020-09-11 16:32:33 -04:00
Sharon Kennedy
52e30336ad handle chat offline signal 2020-09-11 16:32:20 -04:00
Sharon Kennedy
bee884c52f 2.0.1 2020-09-08 08:20:29 -04:00
Sharon Kennedy
2ffa63d583 remove loader when chat is closed 2020-09-08 08:20:23 -04:00
Sharon Kennedy
a0d08f8f88 2.0.0 2020-09-06 15:34:45 -04:00
Sharon Kennedy
09cc934fbd latest build 2020-09-06 15:34:31 -04:00
Sharon
5a0ed5d36d Merge pull request #1 from nomadic-labs/bot_signal
Bot signal
2020-09-06 15:25:31 -04:00
Sharon Kennedy
dbbe188adc update tests 2020-09-06 15:24:41 -04:00
Sharon Kennedy
91bec23c48 handle bot signal 2020-09-06 14:13:04 -04:00
Sharon Kennedy
90815f361a 1.2.2 2020-07-01 00:50:53 -04:00
Sharon Kennedy
4f0abfed09 wait for initial sync before adding listeners 2020-07-01 00:50:34 -04:00
Sharon Kennedy
ad28e4acc5 update readme with new configs 2020-06-27 11:42:25 -04:00
Sharon Kennedy
dcfbf8ae02 1.2.1 2020-06-27 11:31:41 -04:00
Sharon Kennedy
b02ee6282a smaller start chat button on mobile 2020-06-27 11:31:01 -04:00
Sharon Kennedy
3107cf6904 1.2.0 2020-06-25 23:04:00 -04:00
Sharon Kennedy
0fcb7e6e07 build and add profiler 2020-06-25 23:03:22 -04:00
Sharon Kennedy
c80e3269c3 configurable max wait time 2020-06-25 22:20:54 -04:00
Sharon Kennedy
5ed83271d9 configurable size and position of chatbox 2020-06-25 21:56:55 -04:00
Sharon Kennedy
706791cc38 1.1.1 2020-06-11 23:09:23 -04:00
Sharon Kennedy
181a4da221 generic chat unavailable message 2020-06-11 23:08:38 -04:00
Sharon Kennedy
46868b141a 1.1.0 2020-06-11 23:03:05 -04:00
Sharon Kennedy
247bc3e2ba 1.1.1 2020-06-11 23:02:14 -04:00
Sharon Kennedy
29b86e4190 1.1.0 2020-06-11 23:02:03 -04:00
Sharon Kennedy
716f61b183 1.1.1 2020-06-11 23:01:43 -04:00
Sharon Kennedy
516a1e0fbd encrypt by default 2020-06-11 22:59:42 -04:00
Sharon Kennedy
80ecf98be1 1.1.0 2020-06-11 11:01:52 -04:00
Sharon Kennedy
f0b43743f7 add flag to disable encryption 2020-06-11 08:31:46 -04:00
Sharon Kennedy
5252321f56 store messages in object instead of array 2020-06-11 01:54:05 -04:00
Sharon Kennedy
93135daaa8 close chat connection if chat is offline 2020-06-10 17:49:19 -04:00
Sharon Kennedy
f27ebb3c71 move offline messaging to chatbox instead of bot 2020-06-10 16:59:50 -04:00
Sharon Kennedy
7d5ad29b60 use rhok server for demo 2020-05-27 22:22:16 -04:00
Sharon Kennedy
27916c9eef 1.0.2 2020-05-26 10:46:17 -04:00
Sharon Kennedy
b5fb1d0a8b fix font sizing in dark mode 2020-05-26 10:46:06 -04:00
Sharon Kennedy
6070926b89 1.0.1 2020-05-26 09:29:45 -04:00
Sharon Kennedy
8427e82c9d add namespace to avoid css collistions 2020-05-26 09:28:32 -04:00
Sharon Kennedy
f262c9df0f change package name and readme 2020-05-07 15:09:22 -04:00
Sharon Kennedy
b9f822d308 latest build 2020-05-07 14:59:36 -04:00
Sharon Kennedy
0cb939ff7d remove unused files 2020-05-07 14:56:51 -04:00
Sharon Kennedy
057789e741 remove images 2020-05-07 10:25:27 -04:00
56 changed files with 997 additions and 3121 deletions

View File

@@ -1,48 +0,0 @@
version: 2
jobs:
build:
docker:
- image: node:10
steps:
- checkout
- run:
name: dep install
command: npm install
- run:
name: install codecov
command: npm install -g codecov
- run:
name: test
command: npm test && codecov
- run:
name: build
command: |
npm run build
[ -f ./dist/index.html ] || exit 1
[ -f ./dist/blank.html ] || exit 1
[ -f ./dist/widget.js ] || exit 1
[ -f ./dist/bookmarklet.js ] || exit 1
- run:
name: npm start works
command: |
npm run start &
pid=$!
sleep 10s
ps $pid
- run:
name: deploy
command: |
if [ "$CIRCLE_BRANCH" = "master" ]; then
git config --global user.email $GH_EMAIL
git config --global user.name $GH_NAME
npm run deploy
fi
workflows:
version: 2
build-deploy:
jobs:
- build:
filters:
branches:
ignore: gh-pages

View File

@@ -1,2 +0,0 @@
import '@storybook/addon-actions/register';
import '@storybook/addon-links/register';

View File

@@ -1,9 +0,0 @@
import { configure } from '@storybook/react';
// automatically import all files ending in *.stories.js
const req = require.context('../stories', true, /\.stories\.js$/);
function loadStories() {
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);

View File

@@ -1,13 +0,0 @@
const path = require('path');
module.exports = {
module: {
rules: [
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
include: path.resolve(__dirname, '../'),
},
],
},
}

View File

@@ -10,11 +10,11 @@ Built on:
## Usage ## Usage
``` ```
<script src="https://unpkg.com/safesupport-chatbox" type="text/javascript"></script> <script src="https://unpkg.com/private-safesupport-chatbox" type="text/javascript"></script>
<script> <script>
var config = { var config = {
matrixServerUrl: 'https://matrix.rhok.space', matrixServerUrl: 'https://matrix-client.matrix.org',
botId: '@help-bot:rhok.space', botId: '@your-help-bot:matrix.org',
roomName: 'Support Chat', roomName: 'Support Chat',
termsUrl: 'https://tosdr.org/', termsUrl: 'https://tosdr.org/',
introMessage: 'This chat application does not collect any of your personal data or any data from your use of this service.', introMessage: 'This chat application does not collect any of your personal data or any data from your use of this service.',
@@ -31,8 +31,8 @@ Built on:
Options: Options:
| Name | Description | Default | Name | Description | Default
| ----------- | ----------- | --------- | | ----------- | ----------- | --------- |
| `matrixServerUrl` (required) | URL for the Matrix homeserver you want to connect to | `https://matrix.rhok.space` | | `matrixServerUrl` (required) | URL for the Matrix homeserver you want to connect to | `https://matrix-client.matrix.org` |
| `botId` (required) | User ID for the bot account that handles invites | `@help-bot:rhok.space` | | `botId` (required) | User ID for the bot account that handles invites | null |
| `introMessage` (optional) | First message the user sees before agreeing to the Terms of Use | `This chat application does not collect any of your personal data or any data from your use of this service.` | | `introMessage` (optional) | First message the user sees before agreeing to the Terms of Use | `This chat application does not collect any of your personal data or any data from your use of this service.` |
| `termsUrl` (optional) | URL for the Terms of Use for the chat service | `https://tosdr.org/` | | `termsUrl` (optional) | URL for the Terms of Use for the chat service | `https://tosdr.org/` |
| `roomName` (optional) | Name of the chatroom generated in Riot | 'Support Chat' | | `roomName` (optional) | Name of the chatroom generated in Riot | 'Support Chat' |
@@ -40,7 +40,13 @@ Options:
| `confirmationMessage` (optional) | Text to show to ask for agreement to continue | `Waiting for a facilitator to join the chat...` | | `confirmationMessage` (optional) | Text to show to ask for agreement to continue | `Waiting for a facilitator to join the chat...` |
| `exitMessage` (optional) | Text to show if the user rejects the Terms of Use. | `The chat is closed. You may close this window.` | | `exitMessage` (optional) | Text to show if the user rejects the Terms of Use. | `The chat is closed. You may close this window.` |
| `anonymousDisplayName` (optional) | The display name for the chat user. | `Anonymous` | | `anonymousDisplayName` (optional) | The display name for the chat user. | `Anonymous` |
| `chatUnavailableMessage` (optional) | Text to show if no-one is available to respond | `The chat service is not available right now. Please try again later.` | | `chatUnavailableMessage` (optional) | Text to show on error or if the service is otherwise unavailable | `The chat service is not available right now. Please try again later.` |
| `waitMessage` (optional) | Text to show if there is at least one facilitator online but they do not respond right away | `Please be patient, our online facilitators are currently responding to other support requests.` |
| `chatOfflineMessage` (optional) | Text to show if there is no-one online respond | `All of the chat facilitators are currently offline.` |
| `size` (optional) | The size of the start button. Can be 'small' or 'large' | `large` |
| `position` (optional) | The position of the start button. Can be 'top left', 'top right', 'bottom left', 'bottom right'. | `bottom right` |
| `waitInterval` (optional) | The interval (in ms) at which the bot sends the wait message | 120000 |
## Feature list ## Feature list

View File

@@ -24,7 +24,13 @@ export const mockInitCrypto = jest.fn()
export const mockStartClient = jest.fn(() => { export const mockStartClient = jest.fn(() => {
return Promise.resolve('value'); return Promise.resolve('value');
}); });
export const mockOnce = jest.fn() export const mockOnce = jest
.fn()
.mockImplementation((event, callback) => {
if (event === 'sync') {
callback('PREPARED')
}
})
export const mockStopClient = jest.fn(() => { export const mockStopClient = jest.fn(() => {
return Promise.resolve('value'); return Promise.resolve('value');
}); });

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 MiB

18
dist/bookmarklet.js vendored

File diff suppressed because one or more lines are too long

18
dist/chatbox.js vendored

File diff suppressed because one or more lines are too long

36
dist/component.js vendored Normal file

File diff suppressed because one or more lines are too long

12
dist/index.html vendored
View File

@@ -13,16 +13,8 @@
<script src="./chatbox.js"></script> <script src="./chatbox.js"></script>
<script> <script>
var config = { var config = {
matrixServerUrl: 'https://matrix.safesupport.chat', settingsEndpoint: 'https://safesupport-admin.herokuapp.com/api/get-settings',
botId: '@help-bot:safesupport.chat', matrixServerUrl: 'https://matrix.safesupport.chat'
roomName: 'Support Chat',
termsUrl: 'https://tosdr.org/',
introMessage: "This chat application does not collect any of your personal data or any data from your use of this service.",
agreementMessage: 'Do you want to continue?',
confirmationMessage: 'Waiting for a facilitator to join the chat...',
exitMessage: 'The chat is closed. You may close this window.',
chatUnavailableMessage: 'The chat service is not available right now. Please try again later.',
anonymousDisplayName: 'Anonymous',
} }
EmbeddableChatbox.mount(config); EmbeddableChatbox.mount(config);

BIN
dist/olm.wasm vendored

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 230 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 296 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 143 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

View File

@@ -1,10 +1,11 @@
{ {
"name": "safesupport-chatbox", "name": "private-safesupport-chatbox",
"version": "1.1.3", "version": "2.3.1",
"description": "A secure and private embeddable chatbox that connects to Riot", "description": "A secure and private embeddable chatbox that connects to Riot",
"main": "dist/chatbox.js", "main": "dist/chatbox.js",
"scripts": { "scripts": {
"build": "NODE_ENV=production webpack-cli --mode production", "build": "NODE_ENV=production webpack-cli --mode production",
"build:profile": "webpack --mode production --config webpack.config.profile.js",
"start": "webpack-dev-server", "start": "webpack-dev-server",
"test": "jest", "test": "jest",
"test-update-snapshots": "jest --updateSnapshot", "test-update-snapshots": "jest --updateSnapshot",
@@ -76,7 +77,7 @@
"author": "Nomadic Labs <sharon@nomadiclabs.ca", "author": "Nomadic Labs <sharon@nomadiclabs.ca",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@babel/core": "7.7.7", "@babel/core": "^7.10.3",
"@babel/plugin-proposal-class-properties": "7.7.4", "@babel/plugin-proposal-class-properties": "7.7.4",
"@babel/plugin-proposal-decorators": "7.7.4", "@babel/plugin-proposal-decorators": "7.7.4",
"@babel/plugin-proposal-export-namespace-from": "7.7.4", "@babel/plugin-proposal-export-namespace-from": "7.7.4",
@@ -89,10 +90,6 @@
"@babel/plugin-transform-runtime": "^7.9.0", "@babel/plugin-transform-runtime": "^7.9.0",
"@babel/preset-env": "^7.9.0", "@babel/preset-env": "^7.9.0",
"@babel/preset-react": "^7.9.4", "@babel/preset-react": "^7.9.4",
"@storybook/addon-actions": "5.2.8",
"@storybook/addon-links": "5.2.8",
"@storybook/addons": "5.2.8",
"@storybook/react": "5.2.8",
"autoprefixer": "^9.7.5", "autoprefixer": "^9.7.5",
"babel-core": "7.0.0-bridge.0", "babel-core": "7.0.0-bridge.0",
"babel-eslint": "10.0.3", "babel-eslint": "10.0.3",
@@ -121,16 +118,20 @@
"node-sass": "^4.13.1", "node-sass": "^4.13.1",
"postcss-increase-specificity": "0.6.0", "postcss-increase-specificity": "0.6.0",
"postcss-loader": "3.0.0", "postcss-loader": "3.0.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"sass-loader": "8.0.0", "sass-loader": "8.0.0",
"style-loader": "1.1.2", "style-loader": "1.1.2",
"wait-for-expect": "^3.0.2", "wait-for-expect": "^3.0.2",
"webpack": "4.41.5", "webpack": "4.41.5",
"webpack-bundle-analyzer": "^3.8.0",
"webpack-cli": "3.3.10", "webpack-cli": "3.3.10",
"webpack-dev-server": "3.10.1", "webpack-dev-server": "3.10.1",
"webpack-obfuscator": "0.22.0", "webpack-obfuscator": "0.22.0",
"webpack-serve": "3.2.0" "webpack-serve": "3.2.0"
}, },
"dependencies": { "dependencies": {
"airtable": "^0.10.0",
"browser-encrypt-attachment": "^0.3.0", "browser-encrypt-attachment": "^0.3.0",
"emoji-picker-react": "^3.1.3", "emoji-picker-react": "^3.1.3",
"isomorphic-fetch": "^2.2.1", "isomorphic-fetch": "^2.2.1",
@@ -139,11 +140,13 @@
"node-localstorage": "^2.1.5", "node-localstorage": "^2.1.5",
"olm": "https://packages.matrix.org/npm/olm/olm-3.1.4.tgz", "olm": "https://packages.matrix.org/npm/olm/olm-3.1.4.tgz",
"prop-types": "^15.6.2", "prop-types": "^15.6.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-onclickoutside": "^6.9.0", "react-onclickoutside": "^6.9.0",
"react-test-renderer": "^16.13.0", "react-test-renderer": "^16.13.0",
"react-transition-group": "^4.0.0", "react-transition-group": "^4.0.0",
"uuidv4": "^6.0.2" "uuidv4": "^6.0.2"
},
"peerDependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6"
} }
} }

View File

@@ -13,18 +13,8 @@
<script src="./chatbox.js"></script> <script src="./chatbox.js"></script>
<script> <script>
var config = { var config = {
matrixServerUrl: 'https://matrix.safesupport.chat', matrixServerUrl: 'https://matrix.safesupport.chat'
botId: '@help-bot:safesupport.chat', };
roomName: 'Support Chat',
termsUrl: 'https://tosdr.org/',
introMessage: "This chat application does not collect any of your personal data or any data from your use of this service.",
agreementMessage: 'Do you want to continue?',
confirmationMessage: 'Waiting for a facilitator to join the chat...',
exitMessage: 'The chat is closed. You may close this window.',
chatUnavailableMessage: 'The chat service is not available right now. Please try again later.',
anonymousDisplayName: 'Anonymous',
}
EmbeddableChatbox.mount(config); EmbeddableChatbox.mount(config);
</script> </script>

Binary file not shown.

View File

@@ -0,0 +1,98 @@
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import Chatbox from './chatbox';
import { DEFAULT_SETTINGS_ENDPOINT } from '../utils/constants';
const ChatboxWithSettings = ({ settingsEndpoint = null, matrixServerUrl, ...rest }) => {
const [settings, setSettings] = useState({});
const [shifts, setShifts] = useState();
const [isAvailable, setAvailability] = useState(false);
const getSettings = async () => {
const endpoint = settingsEndpoint || DEFAULT_SETTINGS_ENDPOINT;
const url = `${endpoint}?homeserver=${encodeURIComponent(matrixServerUrl)}`;
const res = await fetch(url);
const data = await res.json();
const { fields, schedule = [] } = data;
if (!fields) {
const props = {
...rest,
enabled: true,
isAvailable: true,
};
return setSettings(props);
}
const settingsObj = {};
setShifts(schedule);
Object.entries(fields).forEach(([k, v]) => {
const [scope, key] = k.split('_');
if (scope === 'web') {
settingsObj[key] = v;
}
});
if (!settingsObj.enabled) {
settingsObj.enabled = false;
}
return setSettings(settingsObj);
};
const checkSchedule = () => {
if (shifts.length === 0) {
setAvailability(true);
}
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const now = new Date();
const weekday = weekdays[now.getDay()];
const hours = now.getHours();
const minutes = now.getMinutes();
shifts.map(async (shift) => {
const [startHours, startMinutes] = shift.start.split(':').map((t) => Number(t));
const [endHours, endMinutes] = shift.end.split(':').map((t) => Number(t));
if (
shift.service === 'web'
&& shift.weekday === weekday
&& ((startHours < hours) || (startHours === hours && startMinutes <= minutes))
&& ((endHours > hours) || (endHours === hours && endMinutes > minutes))
) {
setAvailability(true);
}
});
};
useEffect(() => {
getSettings();
}, []);
useEffect(() => {
if (shifts) {
checkSchedule();
}
}, [shifts]);
return (
/* eslint-disable react/jsx-props-no-spreading */
<Chatbox matrixServerUrl={matrixServerUrl} isAvailable={isAvailable} {...settings} {...rest} />
);
};
ChatboxWithSettings.propTypes = {
matrixServerUrl: PropTypes.string.isRequired,
settingsEndpoint: PropTypes.string,
};
ChatboxWithSettings.defaultProps = {
settingsEndpoint: null,
};
export default ChatboxWithSettings;

View File

@@ -26,14 +26,56 @@
} }
} }
@keyframes slideInDown {
from {
transform: translate3d(0, -100%, 0);
display: inherit;
visibility: visible;
}
to {
transform: translate3d(0, 0, 0);
}
}
@keyframes slideOutUp {
from {
transform: translate3d(0, 0, 0);
}
to {
display: none;
visibility: hidden;
transform: translate3d(0, -100%, 0);
}
}
.docked-widget { .docked-widget {
position: fixed; position: fixed;
bottom: 10px;
right: 10px;
z-index: 9999; z-index: 9999;
width: 400px;
max-width: 100vw; max-width: 100vw;
font-size: $base-font-size; font-size: $base-font-size;
&.size-large {
width: 400px;
.dock {
width: 400px;
}
}
&.size-small {
#open-chatbox-label {
display: flex;
align-items: center;
.icon {
margin-left: 0.5em;
font-size: 1.2em;
}
}
}
} }
.dock { .dock {
@@ -41,7 +83,6 @@
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
width: 400px;
max-width: calc(100vw - 10px); max-width: calc(100vw - 10px);
color: $white; color: $white;
font-family: $theme-font; font-family: $theme-font;
@@ -53,6 +94,7 @@
background-color: transparent; background-color: transparent;
padding: 5px; padding: 5px;
#open-chatbox-label { #open-chatbox-label {
background: $theme-color; background: $theme-color;
padding: 0.75em; padding: 0.75em;
@@ -99,11 +141,16 @@
width: 400px; width: 400px;
max-width: calc(100vw - 10px); max-width: calc(100vw - 10px);
border-bottom: none; border-bottom: none;
margin: 0;
animation-duration: 0.2s; animation-duration: 0.2s;
animation-fill-mode: forwards; animation-fill-mode: forwards;
&-entering { &-entering {
animation-name: slideInUp; animation-name: slideInUp;
&.position-top {
animation-name: slideInDown;
}
} }
&-entered { &-entered {
display: inherit; display: inherit;
@@ -111,6 +158,10 @@
} }
&-exiting { &-exiting {
animation-name: slideOutDown; animation-name: slideOutDown;
&.position-top {
animation-name: slideOutUp;
}
} }
&-exited { &-exited {
display: none; display: none;
@@ -520,6 +571,16 @@
} }
@media screen and (max-width: 420px){ @media screen and (max-width: 420px){
.docked-widget {
.dock {
justify-content: flex-end;
}
#open-chatbox-label {
flex: 0 1 auto;
}
}
.docked-widget { .docked-widget {
right: 0; right: 0;
left: 0; left: 0;

View File

@@ -68,7 +68,6 @@
.message { .message {
&.from-bot { &.from-bot {
color: transparentize($light-text-color, 0.3); color: transparentize($light-text-color, 0.3);
font-size: 0.9rem;
} }
&.from-me { &.from-me {

View File

@@ -24,8 +24,7 @@ const ENCRYPTION_CONFIG = { "algorithm": "m.megolm.v1.aes-sha2" };
const ENCRYPTION_NOTICE = "Messages in this chat are secured with end-to-end encryption." const ENCRYPTION_NOTICE = "Messages in this chat are secured with end-to-end encryption."
const UNENCRYPTION_NOTICE = "Messages in this chat are not encrypted." const UNENCRYPTION_NOTICE = "Messages in this chat are not encrypted."
const RESTARTING_UNENCRYPTED_CHAT_MESSAGE = "Restarting chat without encryption." const RESTARTING_UNENCRYPTED_CHAT_MESSAGE = "Restarting chat without encryption."
const WAIT_TIME_MS = 120000 // 2 minutes const CHAT_IS_OFFLINE_NOTICE = "CHAT_OFFLINE"
const CHAT_IS_OFFLINE_NOTICE = "Chat is offline"
const DEFAULT_MATRIX_SERVER = "https://matrix.rhok.space/" const DEFAULT_MATRIX_SERVER = "https://matrix.rhok.space/"
const DEFAULT_BOT_ID = "@help-bot:rhok.space" const DEFAULT_BOT_ID = "@help-bot:rhok.space"
@@ -35,10 +34,16 @@ const DEFAULT_INTRO_MESSAGE = "This chat application does not collect any of you
const DEFAULT_AGREEMENT_MESSAGE = "Do you want to continue?" const DEFAULT_AGREEMENT_MESSAGE = "Do you want to continue?"
const DEFAULT_CONFIRMATION_MESSAGE = "Waiting for a facilitator to join the chat..." const DEFAULT_CONFIRMATION_MESSAGE = "Waiting for a facilitator to join the chat..."
const DEFAULT_EXIT_MESSAGE = "The chat is closed. You may close this window." const DEFAULT_EXIT_MESSAGE = "The chat is closed. You may close this window."
const DEFAULT_ANONYMOUS_DISPLAY_NAME="Anonymous" const DEFAULT_DISPLAY_NAME="Anonymous"
const DEFAULT_CHAT_UNAVAILABLE_MESSAGE = "The chat service is not available right now. Please try again later." const DEFAULT_CHAT_UNAVAILABLE_MESSAGE = "The chat service is not available right now. Please try again later."
const DEFAULT_CHAT_OFFLINE_MESSAGE = "All of the chat facilitators are currently offline."
const DEFAULT_WAIT_MESSAGE = "Please be patient, our online facilitators are currently responding to other support requests." const DEFAULT_WAIT_MESSAGE = "Please be patient, our online facilitators are currently responding to other support requests."
const DEFAULT_ENCRYPTION_DISABLED = false
const DEFAULT_POSITION = 'bottom right'
const DEFAULT_SIZE = 'large'
const DEFAULT_WAIT_INTERVAL_MS = 120000 // 2 minutes
const DEFAULT_DOCK_LABEL = 'Start a new chat'
const DEFAULT_ENABLED = false
class ChatBox extends React.Component { class ChatBox extends React.Component {
constructor(props) { constructor(props) {
@@ -52,7 +57,7 @@ class ChatBox extends React.Component {
userId: null, userId: null,
password: null, password: null,
localStorage: null, localStorage: null,
messages: [], messages: {},
inputValue: "", inputValue: "",
errors: [], errors: [],
roomId: null, roomId: null,
@@ -144,9 +149,8 @@ class ChatBox extends React.Component {
} }
} }
exitChat = async () => { exitChat = async (resetState=true) => {
if (!this.state.client) return null; if (this.state.client) {
await this.state.client.leave(this.state.roomId) await this.state.client.leave(this.state.roomId)
const auth = { const auth = {
@@ -162,10 +166,18 @@ class ChatBox extends React.Component {
await this.state.client.deactivateAccount(auth, true) await this.state.client.deactivateAccount(auth, true)
await this.state.client.stopClient() await this.state.client.stopClient()
await this.state.client.clearStores() await this.state.client.clearStores()
this.setState({ client: null, ready: true }) // no more loading animation
window.clearInterval(this.state.waitIntervalId) // no more waiting messages
}
if (this.state.localStorage) {
this.state.localStorage.clear() this.state.localStorage.clear()
}
if (resetState) {
this.setState(this.initialState) this.setState(this.initialState)
} }
}
createLocalStorage = async (deviceId, sessionId) => { createLocalStorage = async (deviceId, sessionId) => {
let localStorage = global.localStorage; let localStorage = global.localStorage;
@@ -223,23 +235,25 @@ class ChatBox extends React.Component {
this.setState({ ready: false }) this.setState({ ready: false })
const client = await this.createClientWithAccount() const client = await this.createClientWithAccount()
this.setState({
client: client
})
client.setDisplayName(this.props.anonymousDisplayName)
this.setMatrixListeners(client)
try { try {
await client.initCrypto() await client.initCrypto()
} catch(err) { } catch(err) {
return this.initializeUnencryptedChat() return this.restartWithoutCrypto()
} }
await client.startClient() await client.startClient()
client.once('sync', async (state, prevState, data) => {
if (state === "PREPARED") {
this.setState({ client })
client.setDisplayName(this.props.displayName)
this.setMatrixListeners(client)
await this.createRoom(client) await this.createRoom(client)
} }
})
}
initializeUnencryptedChat = async () => { restartWithoutCrypto = async () => {
if (this.state.client) { if (this.state.client) {
this.state.client.leave(this.state.roomId) this.state.client.leave(this.state.roomId)
this.state.client.stopClient() this.state.client.stopClient()
@@ -268,21 +282,35 @@ class ChatBox extends React.Component {
let client; let client;
client = matrix.createClient(opts) client = matrix.createClient(opts)
this.setState({
client: client,
})
try {
this.setMatrixListeners(client)
client.setDisplayName(this.props.anonymousDisplayName)
await this.createRoom(client)
await client.startClient() await client.startClient()
client.once('sync', async (state, prevState, data) => {
if (state === "PREPARED") {
try {
this.setState({ client })
client.setDisplayName(this.props.displayName)
this.setMatrixListeners(client)
await this.createRoom(client)
this.displayBotMessage({ body: UNENCRYPTION_NOTICE }) this.displayBotMessage({ body: UNENCRYPTION_NOTICE })
} catch(err) { } catch(err) {
console.log("error", err) console.log("error", err)
this.handleInitError(err) this.handleInitError(err)
} }
}
})
}
initializeUnencryptedChat = async () => {
this.setState({ ready: false })
const client = await this.createClientWithAccount()
await client.startClient()
client.once('sync', async (state, prevState, data) => {
client.setDisplayName(this.props.displayName)
this.setMatrixListeners(client)
await this.createRoom(client)
})
} }
handleInitError = (err) => { handleInitError = (err) => {
@@ -292,17 +320,8 @@ class ChatBox extends React.Component {
} }
handleDecryptionError = async (event, err) => { handleDecryptionError = async (event, err) => {
if (this.state.client) {
const isCryptoEnabled = await this.state.client.isCryptoEnabled()
const isRoomEncrypted = this.state.client.isRoomEncrypted(this.state.roomId)
if (!isCryptoEnabled || !isRoomEncrypted) {
return this.initializeUnencryptedChat()
}
}
const eventId = event.getId() const eventId = event.getId()
this.displayFakeMessage({ body: '** Unable to decrypt message **' }, event.getSender(), eventId) this.handleMessageEvent(event)
this.setState({ decryptionErrors: { [eventId]: true }}) this.setState({ decryptionErrors: { [eventId]: true }})
} }
@@ -376,31 +395,39 @@ class ChatBox extends React.Component {
} }
displayFakeMessage = (content, sender, messageId=uuid()) => { displayFakeMessage = (content, sender, messageId=uuid()) => {
const msgList = [...this.state.messages]
const msg = { const msg = {
id: messageId, id: messageId,
type: 'm.room.message', type: 'm.room.message',
sender: sender, sender: sender,
roomId: this.state.roomId, roomId: this.state.roomId,
content: content, content: content,
} timestamp: Date.now(),
msgList.push(msg)
this.setState({ messages: msgList })
} }
displayBotMessage = (content, roomId) => { this.setState({
const msgList = [...this.state.messages] messages: {
...this.state.messages,
[messageId]: msg
}
})
}
displayBotMessage = (content, roomId, messageId=uuid()) => {
const msg = { const msg = {
id: uuid(), id: messageId,
type: 'm.room.message', type: 'm.room.message',
sender: this.props.botId, sender: this.props.botId,
roomId: roomId || this.state.roomId, roomId: roomId || this.state.roomId,
content: content, content: content,
timestamp: Date.now(),
} }
msgList.push(msg)
this.setState({ messages: msgList }) this.setState({
messages: {
...this.state.messages,
[messageId]: msg
}
})
} }
handleMessageEvent = event => { handleMessageEvent = event => {
@@ -410,8 +437,12 @@ class ChatBox extends React.Component {
sender: event.getSender(), sender: event.getSender(),
roomId: event.getRoomId(), roomId: event.getRoomId(),
content: event.getContent(), content: event.getContent(),
timestamp: event.getTs(),
} }
// there's also event.getClearContent() which only works on encrypted messages
// but not really sure when it should be used vs event.getContent()
if (message.content.showToUser && message.content.showToUser !== this.state.userId) { if (message.content.showToUser && message.content.showToUser !== this.state.userId) {
return; return;
} }
@@ -427,23 +458,18 @@ class ChatBox extends React.Component {
this.setState({ messagesInFlight }) this.setState({ messagesInFlight })
} }
// check for decryption error message and replace with decrypted message
// or push message to messages array
const messages = [...this.state.messages]
const decryptionErrors = {...this.state.decryptionErrors} const decryptionErrors = {...this.state.decryptionErrors}
delete decryptionErrors[message.id] delete decryptionErrors[message.id]
const existingMessageIndex = messages.findIndex(({ id }) => id === message.id)
if (existingMessageIndex > -1) { this.setState({
messages.splice(existingMessageIndex, 1, message) messages: {
} else { ...this.state.messages,
messages.push(message) [message.id]: message,
},
decryptionErrors
})
} }
this.setState({ messages, decryptionErrors })
}
handleKeyDown = (e) => { handleKeyDown = (e) => {
switch (e.keyCode) { switch (e.keyCode) {
case 27: case 27:
@@ -458,6 +484,21 @@ class ChatBox extends React.Component {
} }
setMatrixListeners = client => { setMatrixListeners = client => {
client.on("sync", (state, prevState, data) => {
switch (state) {
case "ERROR":
// update UI to say "Connection Lost"
break;
case "SYNCING":
// update UI to remove any "Connection Lost" message
break;
case "PREPARED":
// the client instance is ready to be queried.
this.setState({ client: client })
break;
}
});
client.on("Room.timeline", (event, room) => { client.on("Room.timeline", (event, room) => {
const eventType = event.getType() const eventType = event.getType()
const content = event.getContent() const content = event.getContent()
@@ -482,7 +523,7 @@ class ChatBox extends React.Component {
if (eventType === "m.room.member" && content.membership === "join" && sender !== this.props.botId && sender !== this.state.userId) { if (eventType === "m.room.member" && content.membership === "join" && sender !== this.props.botId && sender !== this.state.userId) {
this.verifyAllRoomDevices(client, room) this.verifyAllRoomDevices(client, room)
this.setState({ facilitatorId: sender, ready: true }) this.setState({ facilitatorId: sender, ready: true })
window.clearInterval(this.state.timeoutId) window.clearInterval(this.state.waitIntervalId)
} }
}); });
@@ -492,12 +533,6 @@ class ChatBox extends React.Component {
return this.handleDecryptionError(event, err) return this.handleDecryptionError(event, err)
} }
if (event.getType() === "m.room.message") { if (event.getType() === "m.room.message") {
const content = event.getContent()
if (content.msgtype === "m.notice" && content.body === CHAT_IS_OFFLINE_NOTICE) {
this.setState({ ready: true })
return window.clearInterval(this.state.timeoutId)
}
this.handleMessageEvent(event) this.handleMessageEvent(event)
} }
}); });
@@ -510,10 +545,30 @@ class ChatBox extends React.Component {
this.setState({ typingStatus: null }) this.setState({ typingStatus: null })
} }
}); });
client.on("event", (event) => {
const eventType = event.getType()
const content = event.getContent()
if (eventType === 'm.bot.signal') {
this.handleBotSignal(content.signal)
}
})
}
handleBotSignal = (signal) => {
switch (signal) {
case 'END_CHAT':
this.displayBotMessage({ body: this.props.exitMessage })
return this.exitChat(false); // keep chat state
case 'CHAT_OFFLINE':
this.displayBotMessage({ body: this.props.chatOfflineMessage })
return this.exitChat(false); // keep chat state
}
} }
componentDidUpdate(prevProps, prevState) { componentDidUpdate(prevProps, prevState) {
if (prevState.messages.length !== this.state.messages.length) { if ((prevState.messages !== this.state.messages) || (prevState.messagesInFlight !== this.state.messagesInFlight) || (prevState.typingStatus !== this.state.typingStatus)) {
if (this.messageWindow.current.scrollTo) { if (this.messageWindow.current.scrollTo) {
this.messageWindow.current.scrollTo(0, this.messageWindow.current.scrollHeight) this.messageWindow.current.scrollTo(0, this.messageWindow.current.scrollHeight)
} }
@@ -531,14 +586,14 @@ class ChatBox extends React.Component {
} }
componentDidMount() { componentDidMount() {
document.addEventListener("keydown", this.handleKeyDown, false); document.addEventListener("keydown", this.handleKeyDown, false)
window.addEventListener('beforeunload', this.exitChat) window.addEventListener('beforeunload', this.exitChat)
} }
componentWillUnmount() { componentWillUnmount() {
document.removeEventListener("keydown", this.handleKeyDown, false); document.removeEventListener("keydown", this.handleKeyDown, false)
window.removeEventListener('beforeunload', this.exitChat) window.removeEventListener('beforeunload', this.exitChat)
this.exitChat(); this.exitChat()
} }
handleInputChange = e => { handleInputChange = e => {
@@ -549,20 +604,24 @@ class ChatBox extends React.Component {
this.setState({ awaitingAgreement: false }) this.setState({ awaitingAgreement: false })
this.startWaitTimeForFacilitator() this.startWaitTimeForFacilitator()
try { try {
if (this.props.isEncryptionDisabled) {
this.initializeUnencryptedChat()
} else {
this.initializeChat() this.initializeChat()
}
} catch(err) { } catch(err) {
this.handleInitError(err) this.handleInitError(err)
} }
} }
startWaitTimeForFacilitator = () => { startWaitTimeForFacilitator = () => {
const timeoutId = window.setInterval(() => { const waitIntervalId = window.setInterval(() => {
if (!this.state.facilitatorId) { if (!this.state.facilitatorId && !this.state.ready) {
this.displayBotMessage({ body: this.props.waitMessage }) this.displayBotMessage({ body: this.props.waitMessage })
} }
}, WAIT_TIME_MS) }, this.props.waitInterval)
this.setState({ timeoutId }) this.setState({ waitIntervalId })
} }
handleRejectTerms = () => { handleRejectTerms = () => {
@@ -575,7 +634,7 @@ class ChatBox extends React.Component {
const message = this.state.inputValue const message = this.state.inputValue
if (!Boolean(message)) return null; if (!Boolean(message)) return null;
if (this.state.isCryptoEnabled && !(this.state.client.isRoomEncrypted(this.state.roomId) && this.state.client.isCryptoEnabled())) return null; if (this.state.isCryptoEnabled && this.state.client && !(this.state.client.isRoomEncrypted(this.state.roomId) && this.state.client.isCryptoEnabled())) return null;
if (this.state.client && this.state.roomId) { if (this.state.client && this.state.roomId) {
const messagesInFlight = [...this.state.messagesInFlight] const messagesInFlight = [...this.state.messagesInFlight]
@@ -595,15 +654,22 @@ class ChatBox extends React.Component {
} }
render() { render() {
if (!this.props.enabled || !this.props.isAvailable) {
return null
}
const { ready, messages, messagesInFlight, inputValue, userId, roomId, typingStatus, opened, showDock, emojiSelectorOpen, isMobile, decryptionErrors } = this.state; const { ready, messages, messagesInFlight, inputValue, userId, roomId, typingStatus, opened, showDock, emojiSelectorOpen, isMobile, decryptionErrors } = this.state;
const orderedMessages = Object.values(messages).sort((a,b) => a.timestamp - b.timestamp)
const inputLabel = 'Send a message...' const inputLabel = 'Send a message...'
const [positionY, positionX] = this.props.position.split(' ')
return ( return (
<div className="docked-widget" role="complementary"> <div id="safesupport">
<div className={`docked-widget size-${this.props.size}`} role="complementary" style={{ [positionY]: '10px', [positionX]: '10px' }}>
<Transition in={opened} timeout={250} onExited={this.handleWidgetExit} onEntered={this.handleWidgetEnter}> <Transition in={opened} timeout={250} onExited={this.handleWidgetExit} onEntered={this.handleWidgetEnter}>
{(status) => { {(status) => {
return ( return (
<div className={`widget widget-${status}`} aria-hidden={!opened}> <div className={`widget widget-${status} position-${positionY}`} aria-hidden={!opened}>
<div id="safesupport-chatbox" aria-haspopup="dialog"> <div id="safesupport-chatbox" aria-haspopup="dialog">
<Header handleToggleOpen={this.handleToggleOpen} opened={opened} handleExitChat={this.handleExitChat} /> <Header handleToggleOpen={this.handleToggleOpen} opened={opened} handleExitChat={this.handleExitChat} />
@@ -630,7 +696,7 @@ class ChatBox extends React.Component {
</div> </div>
{ {
messages.map((message, index) => { orderedMessages.map((message, index) => {
return( return(
<Message key={message.id} message={message} userId={userId} botId={this.props.botId} client={this.state.client} /> <Message key={message.id} message={message} userId={userId} botId={this.props.botId} client={this.state.client} />
) )
@@ -655,7 +721,7 @@ class ChatBox extends React.Component {
<div className={`message from-bot`}> <div className={`message from-bot`}>
<div className="text buttons"> <div className="text buttons">
{`Restart chat without encryption?`} {`Restart chat without encryption?`}
<button className="btn" id="accept" onClick={this.initializeUnencryptedChat}>RESTART</button> <button className="btn" id="accept" onClick={this.restartWithoutCrypto}>RESTART</button>
</div> </div>
</div> </div>
} }
@@ -694,9 +760,10 @@ class ChatBox extends React.Component {
)} )}
} }
</Transition> </Transition>
{showDock && !roomId && <Dock handleToggleOpen={this.handleToggleOpen} />} {showDock && !roomId && <Dock handleToggleOpen={this.handleToggleOpen} size={this.props.size} label={this.props.dockLabel} />}
{showDock && roomId && <Header handleToggleOpen={this.handleToggleOpen} opened={opened} handleExitChat={this.handleExitChat} />} {showDock && roomId && <Header handleToggleOpen={this.handleToggleOpen} opened={opened} handleExitChat={this.handleExitChat} />}
</div> </div>
</div>
); );
} }
}; };
@@ -711,8 +778,15 @@ ChatBox.propTypes = {
confirmationMessage: PropTypes.string, confirmationMessage: PropTypes.string,
exitMessage: PropTypes.string, exitMessage: PropTypes.string,
chatUnavailableMessage: PropTypes.string, chatUnavailableMessage: PropTypes.string,
anonymousDisplayName: PropTypes.string, displayName: PropTypes.string,
waitMessage: PropTypes.string, waitMessage: PropTypes.string,
chatOfflineMessage: PropTypes.string,
isEncryptionDisabled: PropTypes.bool,
position: PropTypes.oneOf(['top left', 'top right', 'bottom left', 'bottom right']),
size: PropTypes.oneOf(['small', 'large']),
waitInterval: PropTypes.number,
dockLabel: PropTypes.string,
enabled: PropTypes.bool
} }
ChatBox.defaultProps = { ChatBox.defaultProps = {
@@ -724,9 +798,16 @@ ChatBox.defaultProps = {
agreementMessage: DEFAULT_AGREEMENT_MESSAGE, agreementMessage: DEFAULT_AGREEMENT_MESSAGE,
confirmationMessage: DEFAULT_CONFIRMATION_MESSAGE, confirmationMessage: DEFAULT_CONFIRMATION_MESSAGE,
exitMessage: DEFAULT_EXIT_MESSAGE, exitMessage: DEFAULT_EXIT_MESSAGE,
anonymousDisplayName: DEFAULT_ANONYMOUS_DISPLAY_NAME, displayName: DEFAULT_DISPLAY_NAME,
chatUnavailableMessage: DEFAULT_CHAT_UNAVAILABLE_MESSAGE, chatUnavailableMessage: DEFAULT_CHAT_UNAVAILABLE_MESSAGE,
waitMessage: DEFAULT_WAIT_MESSAGE, waitMessage: DEFAULT_WAIT_MESSAGE,
chatOfflineMessage: DEFAULT_CHAT_OFFLINE_MESSAGE,
isEncryptionDisabled: DEFAULT_ENCRYPTION_DISABLED,
position: DEFAULT_POSITION,
size: DEFAULT_SIZE,
waitInterval: DEFAULT_WAIT_INTERVAL_MS,
dockLabel: DEFAULT_DOCK_LABEL,
enabled: DEFAULT_ENABLED,
} }
export default ChatBox; export default ChatBox;

View File

@@ -115,9 +115,7 @@ describe('Chatbox', () => {
expect(createClient).toHaveBeenCalled() expect(createClient).toHaveBeenCalled()
expect(mockInitCrypto).toHaveBeenCalled() expect(mockInitCrypto).toHaveBeenCalled()
expect(mockStartClient).toHaveBeenCalled() expect(mockStartClient).toHaveBeenCalled()
expect(mockCreateRoom).toHaveBeenCalled() expect(mockOnce).toHaveBeenCalled()
expect(mockSetPowerLevel).toHaveBeenCalled()
expect(mockOn).toHaveBeenCalled()
}) })
test('rejecting terms should not start chat', async () => { test('rejecting terms should not start chat', async () => {
@@ -146,6 +144,10 @@ describe('Chatbox', () => {
acceptButton.simulate('click') acceptButton.simulate('click')
await waitForExpect(() => {
expect(mockOnce).toHaveBeenCalled()
});
await waitForExpect(() => { await waitForExpect(() => {
expect(mockCreateRoom).toHaveBeenCalled() expect(mockCreateRoom).toHaveBeenCalled()
}); });
@@ -169,7 +171,7 @@ describe('Chatbox', () => {
}) })
test('decryption failure should lead to a new unencrypted chat', async () => { test('decryption failure should handle the message event and save the event ID in state', async () => {
const chatbox = mount(<Chatbox {...testConfig} />) const chatbox = mount(<Chatbox {...testConfig} />)
const dock = chatbox.find('button.dock') const dock = chatbox.find('button.dock')
const instance = chatbox.instance() const instance = chatbox.instance()
@@ -183,25 +185,25 @@ describe('Chatbox', () => {
acceptButton.simulate('click') acceptButton.simulate('click')
await waitForExpect(() => { await waitForExpect(() => {
expect(mockCreateRoom).toHaveBeenCalled() expect(mockOnce).toHaveBeenCalled()
}); });
jest.spyOn(instance, 'initializeUnencryptedChat') jest.spyOn(instance, 'handleMessageEvent')
instance.handleDecryptionError()
instance.handleDecryptionError({
getId: () => 'test_event_id',
getType: () => 'm.message',
getSender: () => 'sender',
getRoomId: () => 'room id',
getContent: () => ({ body: 'test msg' }),
getTs: () => '123',
})
await waitForExpect(() => { await waitForExpect(() => {
expect(mockLeave).toHaveBeenCalled() expect(instance.handleMessageEvent).toHaveBeenCalled()
}); })
await waitForExpect(() => { expect(chatbox.state().decryptionErrors).toEqual({ 'test_event_id': true })
expect(mockStopClient).toHaveBeenCalled()
});
await waitForExpect(() => {
expect(mockClearStores).toHaveBeenCalled()
});
expect(instance.initializeUnencryptedChat).toHaveBeenCalled()
}) })
test('creating an unencrypted chat', async () => { test('creating an unencrypted chat', async () => {

View File

@@ -1,8 +1,7 @@
import React from "react" import React, { Fragment } from "react"
import PropTypes from "prop-types" import PropTypes from "prop-types"
const Dock = ({ handleToggleOpen }) => { const Dock = ({ handleToggleOpen, size, label }) => {
return( return(
<button <button
type="button" type="button"
@@ -11,10 +10,19 @@ const Dock = ({ handleToggleOpen }) => {
onKeyPress={handleToggleOpen} onKeyPress={handleToggleOpen}
aria-labelledby="open-chatbox-label" aria-labelledby="open-chatbox-label"
> >
<div id="open-chatbox-label">Start a new chat</div> {
size === 'small' ?
<div id="open-chatbox-label">
<span>{label}</span><span className="icon">+</span>
</div>
:
<Fragment>
<div id="open-chatbox-label">{label}</div>
<div className="label-icon"> <div className="label-icon">
<div className={`btn-icon`} aria-label={`Open support chat window`}>+</div> <div className={`btn-icon`} aria-label={`Open support chat window`}>+</div>
</div> </div>
</Fragment>
}
</button> </button>
) )
} }

View File

@@ -1,4 +1,6 @@
#safesupport {
@import "variables"; @import "variables";
@import "loader"; @import "loader";
@import "chat"; @import "chat";
@import "dark_mode"; @import "dark_mode";
}

View File

@@ -1,17 +1,17 @@
import EmbeddableChatbox from './embeddable-chatbox'; import EmbeddableChatbox from './embeddable-chatbox';
const config = { const config = {
matrixServerUrl: 'https://matrix.safesupport.chat', matrixServerUrl: 'https://matrix.rhok.space',
botId: '@help-bot:safesupport.chat', botId: '@help-bot:rhok.space',
roomName: 'Support Chat', roomName: 'Support Chat',
termsUrl: 'https://tosdr.org/', termsUrl: 'https://tosdr.org/',
introMessage: "This chat application does not collect any of your personal data or any data from your use of this service.", introMessage: 'This chat application does not collect any of your personal data or any data from your use of this service.',
agreementMessage: 'Do you want to continue?', agreementMessage: 'Do you want to continue?',
confirmationMessage: 'Waiting for a facilitator to join the chat...', confirmationMessage: 'Waiting for a facilitator to join the chat...',
exitMessage: 'The chat is closed. You may close this window.', exitMessage: 'The chat is closed. You may close this window.',
chatUnavailableMessage: 'The chat service is not available right now. Please try again later.', chatUnavailableMessage: 'The chat service is not available right now. Please try again later.',
anonymousDisplayName: 'Anonymous', anonymousDisplayName: 'Anonymous',
} };
export default function bookmarklet() { export default function bookmarklet() {
if (window.EmbeddableChatbox) { if (window.EmbeddableChatbox) {

3
src/outputs/component.js Normal file
View File

@@ -0,0 +1,3 @@
import Chatbox from '../components/chatbox';
export default Chatbox;

View File

@@ -1,13 +1,14 @@
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import Chatbox from '../components/chatbox'; import ChatboxWithSettings from '../components/ChatboxWithSettings';
import '../../vendor/cleanslate.css'; import '../../vendor/cleanslate.css';
export default class EmbeddableChatbox { export default class EmbeddableChatbox {
static el; static el;
static mount({ parentElement = null, ...props } = {}) { static mount({ parentElement = null, ...props } = {}) {
const component = <Chatbox {...props} />; // eslint-disable-line const component = <ChatboxWithSettings {...props} />; // eslint-disable-line
function doRender() { function doRender() {
if (EmbeddableChatbox.el) { if (EmbeddableChatbox.el) {

3
src/setupTests.js Normal file
View File

@@ -0,0 +1,3 @@
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

1
src/utils/constants.js Normal file
View File

@@ -0,0 +1 @@
export const DEFAULT_SETTINGS_ENDPOINT = 'https://safesupport-admin.herokuapp.com/api/get-settings';

View File

@@ -1,6 +0,0 @@
import React from 'react'
import { storiesOf } from '@storybook/react'
import Widget from '../src/components/widget'
storiesOf(`Widget`)
.add(`default`, () => <Widget />)

View File

@@ -94,4 +94,29 @@ module.exports = [{
publicPath: '/', publicPath: '/',
filename: 'bookmarklet.js', filename: 'bookmarklet.js',
}, },
}, {
...defaultConfig,
entry: './src/outputs/component.js',
output: {
path: distDir,
publicPath: '/',
filename: 'component.js',
library: 'Chatbox',
libraryExport: 'default',
libraryTarget: 'commonjs2',
},
externals: {
react: {
commonjs: "react",
commonjs2: "react",
amd: "React",
root: "React"
},
"react-dom": {
commonjs: "react-dom",
commonjs2: "react-dom",
amd: "ReactDOM",
root: "ReactDOM"
}
}
}]; }];

View File

@@ -0,0 +1,7 @@
const config = require('./webpack.config');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
config[0].plugins = config[0].plugins.concat([new BundleAnalyzerPlugin({ analyzerPort: 5555 })]);
module.exports = config;

3158
yarn.lock

File diff suppressed because it is too large Load Diff