Add manifest.json, icons and install button, flatten client/src
This commit is contained in:
parent
a219e689c1
commit
474afda9c2
105 changed files with 338 additions and 283 deletions
14
client/js/boot.js
Normal file
14
client/js/boot.js
Normal file
|
@ -0,0 +1,14 @@
|
|||
/* eslint-disable no-underscore-dangle */
|
||||
|
||||
// This entrypoint gets inlined in the index page cached by service workers
|
||||
// and is responsible for fetching the data we would otherwise embed
|
||||
|
||||
window.__env__ = fetch('/data', {
|
||||
credentials: 'same-origin'
|
||||
}).then(res => {
|
||||
if (res.ok) {
|
||||
return res.json();
|
||||
}
|
||||
|
||||
throw new Error(res.statusText);
|
||||
});
|
193
client/js/commands.js
Normal file
193
client/js/commands.js
Normal file
|
@ -0,0 +1,193 @@
|
|||
import { COMMAND } from 'state/actions';
|
||||
import { join, part, invite, kick, setTopic } from 'state/channels';
|
||||
import { sendMessage, raw } from 'state/messages';
|
||||
import { setNick, disconnect, whois, away } from 'state/servers';
|
||||
import { select } from 'state/tab';
|
||||
import { find } from 'utils';
|
||||
import createCommandMiddleware, {
|
||||
beforeHandler,
|
||||
notFoundHandler
|
||||
} from './middleware/command';
|
||||
|
||||
const help = [
|
||||
'/join <channel> - Join a channel',
|
||||
'/part [channel] - Leave the current or specified channel',
|
||||
'/nick <nick> - Change nick',
|
||||
'/quit - Disconnect from the current server',
|
||||
'/me <message> - Send action message',
|
||||
'/topic [topic] - Show or set topic in the current channel',
|
||||
'/msg <target> <message> - Send message to the specified channel or user',
|
||||
'/say <message> - Send message to the current chat',
|
||||
'/invite <nick> [channel] - Invite user to the current or specified channel',
|
||||
'/kick <nick> - Kick user from the current channel',
|
||||
'/whois <nick> - Get information about user',
|
||||
'/away [message] - Set or clear away message',
|
||||
'/raw [message] - Send raw IRC message to the current server',
|
||||
'/help [command]... - Print help for all or the specified command(s)'
|
||||
];
|
||||
|
||||
const text = content => ({ content });
|
||||
const error = content => ({ content, type: 'error' });
|
||||
const prompt = content => ({ content, type: 'prompt' });
|
||||
const findHelp = cmd =>
|
||||
find(help, line => line.slice(1, line.indexOf(' ')) === cmd);
|
||||
|
||||
export default createCommandMiddleware(COMMAND, {
|
||||
join({ dispatch, server }, channel) {
|
||||
if (channel) {
|
||||
if (channel[0] !== '#') {
|
||||
return error('Bad channel name');
|
||||
}
|
||||
dispatch(join([channel], server));
|
||||
dispatch(select(server, channel));
|
||||
} else {
|
||||
return error('Missing channel');
|
||||
}
|
||||
},
|
||||
|
||||
part({ dispatch, server, channel, isChannel }, partChannel) {
|
||||
if (partChannel) {
|
||||
dispatch(part([partChannel], server));
|
||||
} else if (isChannel) {
|
||||
dispatch(part([channel], server));
|
||||
} else {
|
||||
return error('This is not a channel');
|
||||
}
|
||||
},
|
||||
|
||||
nick({ dispatch, server }, nick) {
|
||||
if (nick) {
|
||||
dispatch(setNick(nick, server));
|
||||
} else {
|
||||
return error('Missing nick');
|
||||
}
|
||||
},
|
||||
|
||||
quit({ dispatch, server }) {
|
||||
dispatch(disconnect(server));
|
||||
},
|
||||
|
||||
me({ dispatch, server, channel }, ...message) {
|
||||
const msg = message.join(' ');
|
||||
if (msg !== '') {
|
||||
dispatch(sendMessage(`\x01ACTION ${msg}\x01`, channel, server));
|
||||
} else {
|
||||
return error('Messages can not be empty');
|
||||
}
|
||||
},
|
||||
|
||||
topic({ dispatch, getState, server, channel }, ...newTopic) {
|
||||
if (newTopic.length > 0) {
|
||||
dispatch(setTopic(newTopic.join(' '), channel, server));
|
||||
} else if (channel) {
|
||||
const { topic } = getState().channels[server][channel];
|
||||
if (topic) {
|
||||
return text(topic);
|
||||
}
|
||||
}
|
||||
return 'No topic set';
|
||||
},
|
||||
|
||||
msg({ dispatch, server }, target, ...message) {
|
||||
if (!target) {
|
||||
return error('Missing nick/channel');
|
||||
}
|
||||
|
||||
const msg = message.join(' ');
|
||||
if (msg !== '') {
|
||||
dispatch(sendMessage(message.join(' '), target, server));
|
||||
dispatch(select(server, target));
|
||||
} else {
|
||||
return error('Messages can not be empty');
|
||||
}
|
||||
},
|
||||
|
||||
say({ dispatch, server, channel }, ...message) {
|
||||
if (!channel) {
|
||||
return error('Messages can only be sent to channels or users');
|
||||
}
|
||||
|
||||
const msg = message.join(' ');
|
||||
if (msg !== '') {
|
||||
dispatch(sendMessage(message.join(' '), channel, server));
|
||||
} else {
|
||||
return error('Messages can not be empty');
|
||||
}
|
||||
},
|
||||
|
||||
invite({ dispatch, server, channel, isChannel }, user, inviteChannel) {
|
||||
if (!inviteChannel && !isChannel) {
|
||||
return error('This is not a channel');
|
||||
}
|
||||
|
||||
if (user && inviteChannel) {
|
||||
dispatch(invite(user, inviteChannel, server));
|
||||
} else if (user && channel) {
|
||||
dispatch(invite(user, channel, server));
|
||||
} else {
|
||||
return error('Missing nick');
|
||||
}
|
||||
},
|
||||
|
||||
kick({ dispatch, server, channel, isChannel }, user) {
|
||||
if (!isChannel) {
|
||||
return error('This is not a channel');
|
||||
}
|
||||
|
||||
if (user) {
|
||||
dispatch(kick(user, channel, server));
|
||||
} else {
|
||||
return error('Missing nick');
|
||||
}
|
||||
},
|
||||
|
||||
whois({ dispatch, server }, user) {
|
||||
if (user) {
|
||||
dispatch(whois(user, server));
|
||||
} else {
|
||||
return error('Missing nick');
|
||||
}
|
||||
},
|
||||
|
||||
away({ dispatch, server }, ...message) {
|
||||
const msg = message.join(' ');
|
||||
dispatch(away(msg, server));
|
||||
if (msg !== '') {
|
||||
return 'Away message set';
|
||||
}
|
||||
return 'Away message cleared';
|
||||
},
|
||||
|
||||
raw({ dispatch, server }, ...message) {
|
||||
if (message.length > 0 && message[0] !== '') {
|
||||
const cmd = `${message[0].toUpperCase()} ${message.slice(1).join(' ')}`;
|
||||
dispatch(raw(cmd, server));
|
||||
return prompt(`=> ${cmd}`);
|
||||
}
|
||||
return [prompt('=> /raw'), error('Missing message')];
|
||||
},
|
||||
|
||||
help(_, ...commands) {
|
||||
if (commands.length > 0) {
|
||||
const cmdHelp = commands.filter(findHelp).map(findHelp);
|
||||
if (cmdHelp.length > 0) {
|
||||
return text(cmdHelp);
|
||||
}
|
||||
return error('Unable to find any help :(');
|
||||
}
|
||||
return text(help);
|
||||
},
|
||||
|
||||
[beforeHandler](_, command, ...params) {
|
||||
if (command !== 'raw') {
|
||||
return prompt(`=> /${command} ${params.join(' ')}`);
|
||||
}
|
||||
},
|
||||
|
||||
[notFoundHandler](ctx, command, ...params) {
|
||||
if (command === command.toUpperCase()) {
|
||||
return this.raw(ctx, command, ...params);
|
||||
}
|
||||
return error(`=> /${command}: No such command`);
|
||||
}
|
||||
});
|
77
client/js/components/App.js
Normal file
77
client/js/components/App.js
Normal file
|
@ -0,0 +1,77 @@
|
|||
import React, { Suspense, lazy } from 'react';
|
||||
import Route from 'containers/Route';
|
||||
import AppInfo from 'components/AppInfo';
|
||||
import TabList from 'components/TabList';
|
||||
import cn from 'classnames';
|
||||
|
||||
const Chat = lazy(() => import('containers/Chat'));
|
||||
const Connect = lazy(() => import('containers/Connect'));
|
||||
const Settings = lazy(() => import('containers/Settings'));
|
||||
|
||||
const App = ({
|
||||
connected,
|
||||
tab,
|
||||
channels,
|
||||
servers,
|
||||
privateChats,
|
||||
showTabList,
|
||||
select,
|
||||
push,
|
||||
hideMenu,
|
||||
newVersionAvailable
|
||||
}) => {
|
||||
const mainClass = cn('main-container', {
|
||||
'off-canvas': showTabList
|
||||
});
|
||||
|
||||
const handleClick = () => {
|
||||
if (showTabList) {
|
||||
hideMenu();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="wrap" onClick={handleClick}>
|
||||
{!connected && (
|
||||
<AppInfo type="error">
|
||||
Connection lost, attempting to reconnect...
|
||||
</AppInfo>
|
||||
)}
|
||||
{newVersionAvailable && (
|
||||
<AppInfo dismissible>
|
||||
A new version of dispatch just got installed, reload to start using
|
||||
it!
|
||||
</AppInfo>
|
||||
)}
|
||||
<div className="app-container">
|
||||
<TabList
|
||||
tab={tab}
|
||||
channels={channels}
|
||||
servers={servers}
|
||||
privateChats={privateChats}
|
||||
showTabList={showTabList}
|
||||
select={select}
|
||||
push={push}
|
||||
/>
|
||||
<div className={mainClass}>
|
||||
<Suspense
|
||||
maxDuration={1000}
|
||||
fallback={<div className="suspense-fallback">...</div>}
|
||||
>
|
||||
<Route name="chat">
|
||||
<Chat />
|
||||
</Route>
|
||||
<Route name="connect">
|
||||
<Connect />
|
||||
</Route>
|
||||
<Route name="settings">
|
||||
<Settings />
|
||||
</Route>
|
||||
</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default App;
|
28
client/js/components/AppInfo.js
Normal file
28
client/js/components/AppInfo.js
Normal file
|
@ -0,0 +1,28 @@
|
|||
import React, { useState } from 'react';
|
||||
import cn from 'classnames';
|
||||
|
||||
const AppInfo = ({ type, children, dismissible }) => {
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
|
||||
if (!dismissed) {
|
||||
const handleDismiss = () => {
|
||||
if (dismissible) {
|
||||
setDismissed(true);
|
||||
}
|
||||
};
|
||||
|
||||
const className = cn('app-info', {
|
||||
[`app-info-${type}`]: type
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={className} onClick={handleDismiss}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export default AppInfo;
|
12
client/js/components/Root.js
Normal file
12
client/js/components/Root.js
Normal file
|
@ -0,0 +1,12 @@
|
|||
import React from 'react';
|
||||
import { Provider } from 'react-redux';
|
||||
import { hot } from 'react-hot-loader';
|
||||
import App from 'containers/App';
|
||||
|
||||
const Root = ({ store }) => (
|
||||
<Provider store={store}>
|
||||
<App />
|
||||
</Provider>
|
||||
);
|
||||
|
||||
export default hot(module)(Root);
|
81
client/js/components/TabList.js
Normal file
81
client/js/components/TabList.js
Normal file
|
@ -0,0 +1,81 @@
|
|||
import React, { PureComponent } from 'react';
|
||||
import classnames from 'classnames';
|
||||
import Button from 'components/ui/Button';
|
||||
import TabListItem from './TabListItem';
|
||||
|
||||
export default class TabList extends PureComponent {
|
||||
handleTabClick = (server, target) => this.props.select(server, target);
|
||||
|
||||
handleConnectClick = () => this.props.push('/connect');
|
||||
|
||||
handleSettingsClick = () => this.props.push('/settings');
|
||||
|
||||
render() {
|
||||
const { tab, channels, servers, privateChats, showTabList } = this.props;
|
||||
const tabs = [];
|
||||
|
||||
const className = classnames('tablist', {
|
||||
'off-canvas': showTabList
|
||||
});
|
||||
|
||||
channels.forEach(server => {
|
||||
const { address } = server;
|
||||
const srv = servers[address];
|
||||
tabs.push(
|
||||
<TabListItem
|
||||
key={address}
|
||||
server={address}
|
||||
content={srv.name}
|
||||
selected={tab.server === address && !tab.name}
|
||||
connected={srv.status.connected}
|
||||
onClick={this.handleTabClick}
|
||||
/>
|
||||
);
|
||||
|
||||
server.channels.forEach(name =>
|
||||
tabs.push(
|
||||
<TabListItem
|
||||
key={address + name}
|
||||
server={address}
|
||||
target={name}
|
||||
content={name}
|
||||
selected={tab.server === address && tab.name === name}
|
||||
onClick={this.handleTabClick}
|
||||
/>
|
||||
)
|
||||
);
|
||||
|
||||
if (privateChats[address] && privateChats[address].length > 0) {
|
||||
tabs.push(
|
||||
<div key={`${address}-pm}`} className="tab-label">
|
||||
Private messages
|
||||
</div>
|
||||
);
|
||||
|
||||
privateChats[address].forEach(nick =>
|
||||
tabs.push(
|
||||
<TabListItem
|
||||
key={address + nick}
|
||||
server={address}
|
||||
target={nick}
|
||||
content={nick}
|
||||
selected={tab.server === address && tab.name === nick}
|
||||
onClick={this.handleTabClick}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<div className="tab-container">{tabs}</div>
|
||||
<div className="side-buttons">
|
||||
<Button onClick={this.handleConnectClick}>+</Button>
|
||||
<i className="icon-user" />
|
||||
<i className="icon-cog" onClick={this.handleSettingsClick} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
26
client/js/components/TabListItem.js
Normal file
26
client/js/components/TabListItem.js
Normal file
|
@ -0,0 +1,26 @@
|
|||
import React, { memo } from 'react';
|
||||
import classnames from 'classnames';
|
||||
|
||||
const TabListItem = ({
|
||||
target,
|
||||
content,
|
||||
server,
|
||||
selected,
|
||||
connected,
|
||||
onClick
|
||||
}) => {
|
||||
const className = classnames({
|
||||
'tab-server': !target,
|
||||
success: !target && connected,
|
||||
error: !target && !connected,
|
||||
selected
|
||||
});
|
||||
|
||||
return (
|
||||
<p className={className} onClick={() => onClick(server, target)}>
|
||||
<span className="tab-content">{content}</span>
|
||||
</p>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(TabListItem);
|
123
client/js/components/pages/Chat/Chat.js
Normal file
123
client/js/components/pages/Chat/Chat.js
Normal file
|
@ -0,0 +1,123 @@
|
|||
import React, { Component } from 'react';
|
||||
import { isChannel } from 'utils';
|
||||
import ChatTitle from './ChatTitle';
|
||||
import Search from './Search';
|
||||
import MessageBox from './MessageBox';
|
||||
import MessageInput from './MessageInput';
|
||||
import UserList from './UserList';
|
||||
|
||||
export default class Chat extends Component {
|
||||
handleCloseClick = () => {
|
||||
const { tab, part, closePrivateChat, disconnect } = this.props;
|
||||
|
||||
if (isChannel(tab)) {
|
||||
part([tab.name], tab.server);
|
||||
} else if (tab.name) {
|
||||
closePrivateChat(tab.server, tab.name);
|
||||
} else {
|
||||
disconnect(tab.server);
|
||||
}
|
||||
};
|
||||
|
||||
handleSearch = phrase => {
|
||||
const { tab, searchMessages } = this.props;
|
||||
if (isChannel(tab)) {
|
||||
searchMessages(tab.server, tab.name, phrase);
|
||||
}
|
||||
};
|
||||
|
||||
handleNickClick = nick => {
|
||||
const { tab, openPrivateChat, select } = this.props;
|
||||
openPrivateChat(tab.server, nick);
|
||||
select(tab.server, nick);
|
||||
};
|
||||
|
||||
handleTitleChange = title => {
|
||||
const { setServerName, tab } = this.props;
|
||||
setServerName(title, tab.server);
|
||||
};
|
||||
|
||||
handleNickChange = nick => {
|
||||
const { setNick, tab } = this.props;
|
||||
setNick(nick, tab.server, true);
|
||||
};
|
||||
|
||||
handleNickEditDone = nick => {
|
||||
const { setNick, tab } = this.props;
|
||||
setNick(nick, tab.server);
|
||||
};
|
||||
|
||||
render() {
|
||||
const {
|
||||
channel,
|
||||
coloredNicks,
|
||||
currentInputHistoryEntry,
|
||||
hasMoreMessages,
|
||||
messages,
|
||||
nick,
|
||||
search,
|
||||
showUserList,
|
||||
status,
|
||||
tab,
|
||||
title,
|
||||
users,
|
||||
|
||||
addFetchedMessages,
|
||||
fetchMessages,
|
||||
inputActions,
|
||||
runCommand,
|
||||
sendMessage,
|
||||
toggleSearch,
|
||||
toggleUserList
|
||||
} = this.props;
|
||||
let chatClass;
|
||||
if (isChannel(tab)) {
|
||||
chatClass = 'chat-channel';
|
||||
} else if (tab.name) {
|
||||
chatClass = 'chat-private';
|
||||
} else {
|
||||
chatClass = 'chat-server';
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={chatClass}>
|
||||
<ChatTitle
|
||||
channel={channel}
|
||||
status={status}
|
||||
tab={tab}
|
||||
title={title}
|
||||
onCloseClick={this.handleCloseClick}
|
||||
onTitleChange={this.handleTitleChange}
|
||||
onToggleSearch={toggleSearch}
|
||||
onToggleUserList={toggleUserList}
|
||||
/>
|
||||
<Search search={search} onSearch={this.handleSearch} />
|
||||
<MessageBox
|
||||
coloredNicks={coloredNicks}
|
||||
hasMoreMessages={hasMoreMessages}
|
||||
messages={messages}
|
||||
tab={tab}
|
||||
onAddMore={addFetchedMessages}
|
||||
onFetchMore={fetchMessages}
|
||||
onNickClick={this.handleNickClick}
|
||||
/>
|
||||
<MessageInput
|
||||
currentHistoryEntry={currentInputHistoryEntry}
|
||||
nick={nick}
|
||||
tab={tab}
|
||||
onCommand={runCommand}
|
||||
onMessage={sendMessage}
|
||||
onNickChange={this.handleNickChange}
|
||||
onNickEditDone={this.handleNickEditDone}
|
||||
{...inputActions}
|
||||
/>
|
||||
<UserList
|
||||
coloredNicks={coloredNicks}
|
||||
showUserList={showUserList}
|
||||
users={users}
|
||||
onNickClick={this.handleNickClick}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
73
client/js/components/pages/Chat/ChatTitle.js
Normal file
73
client/js/components/pages/Chat/ChatTitle.js
Normal file
|
@ -0,0 +1,73 @@
|
|||
import React, { memo } from 'react';
|
||||
import Navicon from 'containers/Navicon';
|
||||
import Editable from 'components/ui/Editable';
|
||||
import { isValidServerName } from 'state/servers';
|
||||
import { isChannel, linkify } from 'utils';
|
||||
|
||||
const ChatTitle = ({
|
||||
status,
|
||||
title,
|
||||
tab,
|
||||
channel,
|
||||
onTitleChange,
|
||||
onToggleSearch,
|
||||
onToggleUserList,
|
||||
onCloseClick
|
||||
}) => {
|
||||
let closeTitle;
|
||||
if (isChannel(tab)) {
|
||||
closeTitle = 'Leave';
|
||||
} else if (tab.name) {
|
||||
closeTitle = 'Close';
|
||||
} else {
|
||||
closeTitle = 'Disconnect';
|
||||
}
|
||||
|
||||
let serverError = null;
|
||||
if (!tab.name && status.error) {
|
||||
serverError = (
|
||||
<span className="chat-topic error">
|
||||
Error:
|
||||
{status.error}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="chat-title-bar">
|
||||
<Navicon />
|
||||
<Editable
|
||||
className="chat-title"
|
||||
editable={!tab.name}
|
||||
value={title}
|
||||
validate={isValidServerName}
|
||||
onChange={onTitleChange}
|
||||
>
|
||||
<span className="chat-title">{title}</span>
|
||||
</Editable>
|
||||
<div className="chat-topic-wrap">
|
||||
<span className="chat-topic">
|
||||
{channel && linkify(channel.topic)}
|
||||
</span>
|
||||
{serverError}
|
||||
</div>
|
||||
<i className="icon-search" title="Search" onClick={onToggleSearch} />
|
||||
<i
|
||||
className="icon-cancel button-leave"
|
||||
title={closeTitle}
|
||||
onClick={onCloseClick}
|
||||
/>
|
||||
<i className="icon-user button-userlist" onClick={onToggleUserList} />
|
||||
</div>
|
||||
<div className="userlist-bar">
|
||||
<i className="icon-user" />
|
||||
<span className="chat-usercount">
|
||||
{channel && channel.users.length}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(ChatTitle);
|
38
client/js/components/pages/Chat/Message.js
Normal file
38
client/js/components/pages/Chat/Message.js
Normal file
|
@ -0,0 +1,38 @@
|
|||
import React, { memo } from 'react';
|
||||
import classnames from 'classnames';
|
||||
import stringToRGB from 'utils/color';
|
||||
|
||||
const Message = ({ message, coloredNick, style, onNickClick }) => {
|
||||
const className = classnames('message', {
|
||||
[`message-${message.type}`]: message.type
|
||||
});
|
||||
|
||||
style = {
|
||||
...style,
|
||||
paddingLeft: `${window.messageIndent + 15}px`,
|
||||
textIndent: `-${window.messageIndent}px`
|
||||
};
|
||||
|
||||
const senderStyle = {};
|
||||
if (message.from && coloredNick) {
|
||||
senderStyle.color = stringToRGB(message.from);
|
||||
}
|
||||
|
||||
return (
|
||||
<p className={className} style={style}>
|
||||
<span className="message-time">{message.time} </span>
|
||||
{message.from && (
|
||||
<span
|
||||
className="message-sender"
|
||||
style={senderStyle}
|
||||
onClick={() => onNickClick(message.from)}
|
||||
>
|
||||
{message.from}
|
||||
</span>
|
||||
)}
|
||||
<span> {message.content}</span>
|
||||
</p>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(Message);
|
250
client/js/components/pages/Chat/MessageBox.js
Normal file
250
client/js/components/pages/Chat/MessageBox.js
Normal file
|
@ -0,0 +1,250 @@
|
|||
import React, { PureComponent, createRef } from 'react';
|
||||
import { VariableSizeList as List } from 'react-window';
|
||||
import AutoSizer from 'react-virtualized-auto-sizer';
|
||||
import debounce from 'lodash/debounce';
|
||||
import { getScrollPos, saveScrollPos } from 'utils/scrollPosition';
|
||||
import Message from './Message';
|
||||
|
||||
const fetchThreshold = 600;
|
||||
// The amount of time in ms that needs to pass without any
|
||||
// scroll events happening before adding messages to the top,
|
||||
// this is done to prevent the scroll from jumping all over the place
|
||||
const scrollbackDebounce = 100;
|
||||
|
||||
export default class MessageBox extends PureComponent {
|
||||
list = createRef();
|
||||
outer = createRef();
|
||||
|
||||
addMore = debounce(() => {
|
||||
const { tab, onAddMore } = this.props;
|
||||
this.ready = true;
|
||||
onAddMore(tab.server, tab.name);
|
||||
}, scrollbackDebounce);
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
this.loadScrollPos();
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
const scrollToBottom = this.bottom;
|
||||
|
||||
window.requestAnimationFrame(() => {
|
||||
const { messages } = this.props;
|
||||
|
||||
if (scrollToBottom && messages.length > 0) {
|
||||
this.list.current.scrollToItem(messages.length + 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
if (prevProps.tab !== this.props.tab) {
|
||||
this.loadScrollPos(true);
|
||||
}
|
||||
|
||||
if (this.nextScrollTop > 0) {
|
||||
this.list.current.scrollTo(this.nextScrollTop);
|
||||
this.nextScrollTop = 0;
|
||||
} else if (this.bottom) {
|
||||
this.list.current.scrollToItem(this.props.messages.length + 1);
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.saveScrollPos();
|
||||
}
|
||||
|
||||
getSnapshotBeforeUpdate(prevProps) {
|
||||
if (prevProps.messages !== this.props.messages) {
|
||||
this.list.current.resetAfterIndex(0);
|
||||
}
|
||||
|
||||
if (prevProps.tab !== this.props.tab) {
|
||||
this.saveScrollPos();
|
||||
this.bottom = false;
|
||||
}
|
||||
|
||||
if (prevProps.messages[0] !== this.props.messages[0]) {
|
||||
const { messages, hasMoreMessages } = this.props;
|
||||
|
||||
if (prevProps.tab === this.props.tab) {
|
||||
const addedMessages = messages.length - prevProps.messages.length;
|
||||
let addedHeight = 0;
|
||||
for (let i = 0; i < addedMessages; i++) {
|
||||
addedHeight += messages[i].height;
|
||||
}
|
||||
|
||||
this.nextScrollTop = addedHeight + this.outer.current.scrollTop;
|
||||
|
||||
if (!hasMoreMessages) {
|
||||
this.nextScrollTop -= 93;
|
||||
}
|
||||
}
|
||||
|
||||
this.loading = false;
|
||||
this.ready = false;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
getRowHeight = index => {
|
||||
const { messages, hasMoreMessages } = this.props;
|
||||
|
||||
if (index === 0) {
|
||||
if (hasMoreMessages) {
|
||||
return 100;
|
||||
}
|
||||
return 7;
|
||||
} else if (index === messages.length + 1) {
|
||||
return 7;
|
||||
}
|
||||
return messages[index - 1].height;
|
||||
};
|
||||
|
||||
getItemKey = index => {
|
||||
const { messages } = this.props;
|
||||
|
||||
if (index === 0) {
|
||||
return 'top';
|
||||
} else if (index === messages.length + 1) {
|
||||
return 'bottom';
|
||||
}
|
||||
return messages[index - 1].id;
|
||||
};
|
||||
|
||||
updateScrollKey = () => {
|
||||
const { tab } = this.props;
|
||||
this.scrollKey = `msg:${tab.server}:${tab.name}`;
|
||||
return this.scrollKey;
|
||||
};
|
||||
|
||||
loadScrollPos = scroll => {
|
||||
const pos = getScrollPos(this.updateScrollKey());
|
||||
if (pos >= 0) {
|
||||
this.bottom = false;
|
||||
if (scroll) {
|
||||
this.list.current.scrollTo(pos);
|
||||
} else {
|
||||
this.initialScrollTop = pos;
|
||||
}
|
||||
} else {
|
||||
this.bottom = true;
|
||||
if (scroll) {
|
||||
this.list.current.scrollToItem(this.props.messages.length + 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
saveScrollPos = () => {
|
||||
if (this.bottom) {
|
||||
saveScrollPos(this.scrollKey, -1);
|
||||
} else {
|
||||
saveScrollPos(this.scrollKey, this.outer.current.scrollTop);
|
||||
}
|
||||
};
|
||||
|
||||
fetchMore = () => {
|
||||
this.loading = true;
|
||||
this.props.onFetchMore();
|
||||
};
|
||||
|
||||
handleScroll = ({ scrollOffset, scrollDirection }) => {
|
||||
if (
|
||||
!this.loading &&
|
||||
this.props.hasMoreMessages &&
|
||||
scrollOffset <= fetchThreshold &&
|
||||
scrollDirection === 'backward'
|
||||
) {
|
||||
this.fetchMore();
|
||||
}
|
||||
|
||||
if (this.loading && !this.ready) {
|
||||
if (this.mouseDown) {
|
||||
this.ready = true;
|
||||
this.shouldAdd = true;
|
||||
} else {
|
||||
this.addMore();
|
||||
}
|
||||
}
|
||||
|
||||
const { clientHeight, scrollHeight } = this.outer.current;
|
||||
|
||||
this.bottom = scrollOffset + clientHeight >= scrollHeight - 20;
|
||||
};
|
||||
|
||||
handleMouseDown = () => {
|
||||
this.mouseDown = true;
|
||||
};
|
||||
|
||||
handleMouseUp = () => {
|
||||
this.mouseDown = false;
|
||||
|
||||
if (this.shouldAdd) {
|
||||
const { tab, onAddMore } = this.props;
|
||||
this.shouldAdd = false;
|
||||
onAddMore(tab.server, tab.name);
|
||||
}
|
||||
};
|
||||
|
||||
renderMessage = ({ index, style }) => {
|
||||
const { messages } = this.props;
|
||||
|
||||
if (index === 0) {
|
||||
if (this.props.hasMoreMessages) {
|
||||
return (
|
||||
<div className="messagebox-top-indicator" style={style}>
|
||||
Loading messages...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
} else if (index === messages.length + 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { coloredNicks, onNickClick } = this.props;
|
||||
const message = messages[index - 1];
|
||||
|
||||
return (
|
||||
<Message
|
||||
message={message}
|
||||
coloredNick={coloredNicks}
|
||||
style={style}
|
||||
onNickClick={onNickClick}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div
|
||||
className="messagebox"
|
||||
onMouseDown={this.handleMouseDown}
|
||||
onMouseUp={this.handleMouseUp}
|
||||
>
|
||||
<AutoSizer>
|
||||
{({ width, height }) => (
|
||||
<List
|
||||
ref={this.list}
|
||||
outerRef={this.outer}
|
||||
width={width}
|
||||
height={height}
|
||||
itemCount={this.props.messages.length + 2}
|
||||
itemKey={this.getItemKey}
|
||||
itemSize={this.getRowHeight}
|
||||
estimatedItemSize={32}
|
||||
initialScrollOffset={this.initialScrollTop}
|
||||
onScroll={this.handleScroll}
|
||||
className="messagebox-window"
|
||||
>
|
||||
{this.renderMessage}
|
||||
</List>
|
||||
)}
|
||||
</AutoSizer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
68
client/js/components/pages/Chat/MessageInput.js
Normal file
68
client/js/components/pages/Chat/MessageInput.js
Normal file
|
@ -0,0 +1,68 @@
|
|||
import React, { memo, useState } from 'react';
|
||||
import classnames from 'classnames';
|
||||
import Editable from 'components/ui/Editable';
|
||||
import { isValidNick } from 'utils';
|
||||
|
||||
const MessageInput = ({
|
||||
nick,
|
||||
currentHistoryEntry,
|
||||
onNickChange,
|
||||
onNickEditDone,
|
||||
tab,
|
||||
onCommand,
|
||||
onMessage,
|
||||
add,
|
||||
reset,
|
||||
increment,
|
||||
decrement
|
||||
}) => {
|
||||
const [value, setValue] = useState('');
|
||||
|
||||
const handleKey = e => {
|
||||
if (e.key === 'Enter' && e.target.value) {
|
||||
if (e.target.value[0] === '/') {
|
||||
onCommand(e.target.value, tab.name, tab.server);
|
||||
} else if (tab.name) {
|
||||
onMessage(e.target.value, tab.name, tab.server);
|
||||
}
|
||||
|
||||
add(e.target.value);
|
||||
reset();
|
||||
setValue('');
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
increment();
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
decrement();
|
||||
} else if (currentHistoryEntry) {
|
||||
setValue(e.target.value);
|
||||
reset();
|
||||
}
|
||||
};
|
||||
|
||||
const handleChange = e => setValue(e.target.value);
|
||||
|
||||
return (
|
||||
<div className="message-input-wrap">
|
||||
<Editable
|
||||
className={classnames('message-input-nick', {
|
||||
invalid: !isValidNick(nick)
|
||||
})}
|
||||
value={nick}
|
||||
onBlur={onNickEditDone}
|
||||
onChange={onNickChange}
|
||||
>
|
||||
<span className="message-input-nick">{nick}</span>
|
||||
</Editable>
|
||||
<input
|
||||
className="message-input"
|
||||
type="text"
|
||||
value={currentHistoryEntry || value}
|
||||
onKeyDown={handleKey}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(MessageInput);
|
41
client/js/components/pages/Chat/Search.js
Normal file
41
client/js/components/pages/Chat/Search.js
Normal file
|
@ -0,0 +1,41 @@
|
|||
import React, { memo, useRef, useEffect } from 'react';
|
||||
import SearchResult from './SearchResult';
|
||||
|
||||
const Search = ({ search, onSearch }) => {
|
||||
const inputEl = useRef();
|
||||
|
||||
useEffect(
|
||||
() => {
|
||||
if (search.show) {
|
||||
inputEl.current.focus();
|
||||
}
|
||||
},
|
||||
[search.show]
|
||||
);
|
||||
|
||||
const style = {
|
||||
display: search.show ? 'block' : 'none'
|
||||
};
|
||||
|
||||
let i = 0;
|
||||
const results = search.results.map(result => (
|
||||
<SearchResult key={i++} result={result} />
|
||||
));
|
||||
|
||||
return (
|
||||
<div className="search" style={style}>
|
||||
<div className="search-input-wrap">
|
||||
<i className="icon-search" />
|
||||
<input
|
||||
ref={inputEl}
|
||||
className="search-input"
|
||||
type="text"
|
||||
onChange={e => onSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="search-results">{results}</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(Search);
|
24
client/js/components/pages/Chat/SearchResult.js
Normal file
24
client/js/components/pages/Chat/SearchResult.js
Normal file
|
@ -0,0 +1,24 @@
|
|||
import React, { memo } from 'react';
|
||||
import { timestamp, linkify } from 'utils';
|
||||
|
||||
const SearchResult = ({ result }) => {
|
||||
const style = {
|
||||
paddingLeft: `${window.messageIndent}px`,
|
||||
textIndent: `-${window.messageIndent}px`
|
||||
};
|
||||
|
||||
return (
|
||||
<p className="search-result" style={style}>
|
||||
<span className="message-time">
|
||||
{timestamp(new Date(result.time * 1000))}
|
||||
</span>
|
||||
<span>
|
||||
{' '}
|
||||
<span className="message-sender">{result.from}</span>
|
||||
</span>
|
||||
<span> {linkify(result.content)}</span>
|
||||
</p>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(SearchResult);
|
92
client/js/components/pages/Chat/UserList.js
Normal file
92
client/js/components/pages/Chat/UserList.js
Normal file
|
@ -0,0 +1,92 @@
|
|||
import React, { PureComponent, createRef } from 'react';
|
||||
import { VariableSizeList as List } from 'react-window';
|
||||
import AutoSizer from 'react-virtualized-auto-sizer';
|
||||
import classnames from 'classnames';
|
||||
import UserListItem from './UserListItem';
|
||||
|
||||
export default class UserList extends PureComponent {
|
||||
list = createRef();
|
||||
|
||||
getSnapshotBeforeUpdate(prevProps) {
|
||||
if (this.list.current) {
|
||||
const { users } = this.props;
|
||||
|
||||
if (prevProps.users.length !== users.length) {
|
||||
this.list.current.resetAfterIndex(
|
||||
Math.min(prevProps.users.length, users.length) + 1
|
||||
);
|
||||
} else {
|
||||
this.list.current.forceUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
getItemHeight = index => {
|
||||
const { users } = this.props;
|
||||
|
||||
if (index === 0) {
|
||||
return 12;
|
||||
} else if (index === users.length + 1) {
|
||||
return 10;
|
||||
}
|
||||
return 24;
|
||||
};
|
||||
|
||||
getItemKey = index => {
|
||||
const { users } = this.props;
|
||||
|
||||
if (index === 0) {
|
||||
return 'top';
|
||||
} else if (index === users.length + 1) {
|
||||
return 'bottom';
|
||||
}
|
||||
return index;
|
||||
};
|
||||
|
||||
renderUser = ({ index, style }) => {
|
||||
const { users, coloredNicks, onNickClick } = this.props;
|
||||
|
||||
if (index === 0 || index === users.length + 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<UserListItem
|
||||
user={users[index - 1]}
|
||||
coloredNick={coloredNicks}
|
||||
style={style}
|
||||
onClick={onNickClick}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
render() {
|
||||
const { users, showUserList } = this.props;
|
||||
|
||||
const className = classnames('userlist', {
|
||||
'off-canvas': showUserList
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<AutoSizer disableWidth>
|
||||
{({ height }) => (
|
||||
<List
|
||||
ref={this.list}
|
||||
width={200}
|
||||
height={height}
|
||||
itemCount={users.length + 2}
|
||||
itemKey={this.getItemKey}
|
||||
itemSize={this.getItemHeight}
|
||||
estimatedItemSize={24}
|
||||
>
|
||||
{this.renderUser}
|
||||
</List>
|
||||
)}
|
||||
</AutoSizer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
19
client/js/components/pages/Chat/UserListItem.js
Normal file
19
client/js/components/pages/Chat/UserListItem.js
Normal file
|
@ -0,0 +1,19 @@
|
|||
import React, { memo } from 'react';
|
||||
import stringToRGB from 'utils/color';
|
||||
|
||||
const UserListItem = ({ user, coloredNick, style, onClick }) => {
|
||||
if (coloredNick) {
|
||||
style = {
|
||||
...style,
|
||||
color: stringToRGB(user.nick)
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<p style={style} onClick={() => onClick(user.nick)}>
|
||||
{user.renderName}
|
||||
</p>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(UserListItem);
|
3
client/js/components/pages/Chat/index.js
Normal file
3
client/js/components/pages/Chat/index.js
Normal file
|
@ -0,0 +1,3 @@
|
|||
import Chat from './Chat';
|
||||
|
||||
export default Chat;
|
190
client/js/components/pages/Connect.js
Normal file
190
client/js/components/pages/Connect.js
Normal file
|
@ -0,0 +1,190 @@
|
|||
import React, { Component } from 'react';
|
||||
import { createSelector } from 'reselect';
|
||||
import { Form, withFormik } from 'formik';
|
||||
import Navicon from 'containers/Navicon';
|
||||
import Button from 'components/ui/Button';
|
||||
import Checkbox from 'components/ui/formik/Checkbox';
|
||||
import TextInput from 'components/ui/TextInput';
|
||||
import Error from 'components/ui/formik/Error';
|
||||
import { isValidNick, isValidChannel, isValidUsername, isInt } from 'utils';
|
||||
|
||||
const getSortedDefaultChannels = createSelector(
|
||||
defaults => defaults.channels,
|
||||
channels => channels.split(',').sort()
|
||||
);
|
||||
|
||||
class Connect extends Component {
|
||||
state = {
|
||||
showOptionals: false
|
||||
};
|
||||
|
||||
handleSSLChange = e => {
|
||||
const { values, setFieldValue } = this.props;
|
||||
if (e.target.checked && values.port === 6667) {
|
||||
setFieldValue('port', 6697, false);
|
||||
} else if (!e.target.checked && values.port === 6697) {
|
||||
setFieldValue('port', 6667, false);
|
||||
}
|
||||
};
|
||||
|
||||
handleShowClick = () => {
|
||||
this.setState(prevState => ({ showOptionals: !prevState.showOptionals }));
|
||||
};
|
||||
|
||||
renderOptionals = () => {
|
||||
const { hexIP } = this.props;
|
||||
|
||||
return (
|
||||
<div>
|
||||
{!hexIP && <TextInput name="username" />}
|
||||
<TextInput name="password" type="password" />
|
||||
<TextInput name="realname" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
render() {
|
||||
const { defaults, values } = this.props;
|
||||
const { readOnly, showDetails } = defaults;
|
||||
let form;
|
||||
|
||||
if (readOnly) {
|
||||
form = (
|
||||
<Form className="connect-form">
|
||||
<h1>Connect</h1>
|
||||
{showDetails && (
|
||||
<div className="connect-details">
|
||||
<h2>
|
||||
{values.host}:{values.port}
|
||||
</h2>
|
||||
{getSortedDefaultChannels(values).map(channel => (
|
||||
<p>{channel}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<TextInput name="nick" />
|
||||
<Button type="submit">Connect</Button>
|
||||
</Form>
|
||||
);
|
||||
} else {
|
||||
form = (
|
||||
<Form className="connect-form">
|
||||
<h1>Connect</h1>
|
||||
<TextInput name="name" autoCapitalize="words" />
|
||||
<div className="connect-form-address">
|
||||
<TextInput name="host" noError />
|
||||
<TextInput name="port" type="number" noError />
|
||||
<Checkbox
|
||||
name="tls"
|
||||
label="SSL"
|
||||
topLabel
|
||||
onChange={this.handleSSLChange}
|
||||
/>
|
||||
</div>
|
||||
<Error name="host" />
|
||||
<Error name="port" />
|
||||
<TextInput name="nick" />
|
||||
<TextInput name="channels" />
|
||||
{this.state.showOptionals && this.renderOptionals()}
|
||||
<i className="icon-ellipsis" onClick={this.handleShowClick} />
|
||||
<Button type="submit">Connect</Button>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="connect">
|
||||
<Navicon />
|
||||
{form}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withFormik({
|
||||
enableReinitialize: true,
|
||||
mapPropsToValues: ({ defaults }) => {
|
||||
let port = 6667;
|
||||
if (defaults.port) {
|
||||
({ port } = defaults);
|
||||
} else if (defaults.ssl) {
|
||||
port = 6697;
|
||||
}
|
||||
|
||||
return {
|
||||
name: defaults.name,
|
||||
host: defaults.host,
|
||||
port,
|
||||
nick: '',
|
||||
channels: defaults.channels.join(','),
|
||||
username: '',
|
||||
password: defaults.password ? ' ' : '',
|
||||
realname: '',
|
||||
tls: defaults.ssl
|
||||
};
|
||||
},
|
||||
validate: values => {
|
||||
Object.keys(values).forEach(k => {
|
||||
if (typeof values[k] === 'string') {
|
||||
values[k] = values[k].trim();
|
||||
}
|
||||
});
|
||||
|
||||
const errors = {};
|
||||
|
||||
if (!values.host) {
|
||||
errors.host = 'Host is required';
|
||||
} else if (values.host.indexOf('.') < 1) {
|
||||
errors.host = 'Invalid host';
|
||||
}
|
||||
|
||||
if (!values.port) {
|
||||
values.port = values.tls ? 6697 : 6667;
|
||||
} else if (!isInt(values.port, 1, 65535)) {
|
||||
errors.port = 'Invalid port';
|
||||
}
|
||||
|
||||
if (!values.nick) {
|
||||
errors.nick = 'Nick is required';
|
||||
} else if (!isValidNick(values.nick)) {
|
||||
errors.nick = 'Invalid nick';
|
||||
}
|
||||
|
||||
if (values.username && !isValidUsername(values.username)) {
|
||||
errors.username = 'Invalid username';
|
||||
}
|
||||
|
||||
values.channels = values.channels
|
||||
.split(',')
|
||||
.map(channel => {
|
||||
channel = channel.trim();
|
||||
if (channel) {
|
||||
if (isValidChannel(channel, false)) {
|
||||
if (channel[0] !== '#') {
|
||||
channel = `#${channel}`;
|
||||
}
|
||||
} else {
|
||||
errors.channels = 'Invalid channel(s)';
|
||||
}
|
||||
}
|
||||
return channel;
|
||||
})
|
||||
.filter(s => s)
|
||||
.join(',');
|
||||
|
||||
return errors;
|
||||
},
|
||||
handleSubmit: (values, { props }) => {
|
||||
const { connect, select, join } = props;
|
||||
const channels = values.channels.split(',');
|
||||
delete values.channels;
|
||||
|
||||
values.port = `${values.port}`;
|
||||
connect(values);
|
||||
select(values.host);
|
||||
|
||||
if (channels.length > 0) {
|
||||
join(channels, values.host);
|
||||
}
|
||||
}
|
||||
})(Connect);
|
79
client/js/components/pages/Settings.js
Normal file
79
client/js/components/pages/Settings.js
Normal file
|
@ -0,0 +1,79 @@
|
|||
import React, { useCallback } from 'react';
|
||||
import Navicon from 'containers/Navicon';
|
||||
import Button from 'components/ui/Button';
|
||||
import Checkbox from 'components/ui/Checkbox';
|
||||
import FileInput from 'components/ui/FileInput';
|
||||
|
||||
const Settings = ({
|
||||
settings,
|
||||
installable,
|
||||
setSetting,
|
||||
onCertChange,
|
||||
onKeyChange,
|
||||
onInstall,
|
||||
uploadCert
|
||||
}) => {
|
||||
const status = settings.uploadingCert ? 'Uploading...' : 'Upload';
|
||||
const error = settings.certError;
|
||||
|
||||
const handleInstallClick = useCallback(
|
||||
async () => {
|
||||
installable.prompt();
|
||||
await installable.userChoice;
|
||||
onInstall();
|
||||
},
|
||||
[installable]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="settings-container">
|
||||
<div className="settings">
|
||||
<Navicon />
|
||||
<h1>Settings</h1>
|
||||
{installable && (
|
||||
<Button className="button-install" onClick={handleInstallClick}>
|
||||
<h2>Install</h2>
|
||||
</Button>
|
||||
)}
|
||||
<div className="settings-section">
|
||||
<h2>Visuals</h2>
|
||||
<Checkbox
|
||||
name="coloredNicks"
|
||||
label="Colored nicks"
|
||||
checked={settings.coloredNicks}
|
||||
onChange={e => setSetting('coloredNicks', e.target.checked)}
|
||||
/>
|
||||
</div>
|
||||
<div className="settings-section">
|
||||
<h2>Client Certificate</h2>
|
||||
<div className="settings-cert">
|
||||
<div className="settings-file">
|
||||
<p>Certificate</p>
|
||||
<FileInput
|
||||
name={settings.certFile || 'Select Certificate'}
|
||||
onChange={onCertChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="settings-file">
|
||||
<p>Private Key</p>
|
||||
<FileInput
|
||||
name={settings.keyFile || 'Select Key'}
|
||||
onChange={onKeyChange}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="submit"
|
||||
className="settings-button"
|
||||
onClick={uploadCert}
|
||||
>
|
||||
{status}
|
||||
</Button>
|
||||
{error ? <p className="error">{error}</p> : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Settings;
|
9
client/js/components/ui/Button.js
Normal file
9
client/js/components/ui/Button.js
Normal file
|
@ -0,0 +1,9 @@
|
|||
import React from 'react';
|
||||
|
||||
const Button = ({ children, ...props }) => (
|
||||
<button type="button" {...props}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
|
||||
export default Button;
|
18
client/js/components/ui/Checkbox.js
Normal file
18
client/js/components/ui/Checkbox.js
Normal file
|
@ -0,0 +1,18 @@
|
|||
import React from 'react';
|
||||
import classnames from 'classnames';
|
||||
|
||||
const Checkbox = ({ name, label, topLabel, ...props }) => (
|
||||
<label
|
||||
className={classnames('checkbox', {
|
||||
'top-label': topLabel
|
||||
})}
|
||||
htmlFor={name}
|
||||
>
|
||||
{topLabel && label}
|
||||
<input type="checkbox" id={name} name={name} {...props} />
|
||||
<span />
|
||||
{!topLabel && label}
|
||||
</label>
|
||||
);
|
||||
|
||||
export default Checkbox;
|
107
client/js/components/ui/Editable.js
Normal file
107
client/js/components/ui/Editable.js
Normal file
|
@ -0,0 +1,107 @@
|
|||
import React, { PureComponent, createRef } from 'react';
|
||||
import { stringWidth } from 'utils';
|
||||
|
||||
export default class Editable extends PureComponent {
|
||||
static defaultProps = {
|
||||
editable: true
|
||||
};
|
||||
|
||||
inputEl = createRef();
|
||||
|
||||
state = {
|
||||
editing: false
|
||||
};
|
||||
|
||||
componentDidUpdate(prevProps, prevState) {
|
||||
if (!prevState.editing && this.state.editing) {
|
||||
// eslint-disable-next-line react/no-did-update-set-state
|
||||
this.updateInputWidth(this.props.value);
|
||||
this.inputEl.current.focus();
|
||||
}
|
||||
}
|
||||
|
||||
getSnapshotBeforeUpdate(prevProps) {
|
||||
if (this.state.editing && prevProps.value !== this.props.value) {
|
||||
this.updateInputWidth(this.props.value);
|
||||
}
|
||||
}
|
||||
|
||||
updateInputWidth = value => {
|
||||
if (this.inputEl.current) {
|
||||
const style = window.getComputedStyle(this.inputEl.current);
|
||||
const padding = parseInt(style.paddingRight, 10);
|
||||
// Make sure the width is at least 1px so the caret always shows
|
||||
const width =
|
||||
stringWidth(value, `${style.fontSize} ${style.fontFamily}`) || 1;
|
||||
|
||||
this.setState({
|
||||
width: width + padding * 2,
|
||||
indent: padding
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
startEditing = () => {
|
||||
if (this.props.editable) {
|
||||
this.initialValue = this.props.value;
|
||||
this.setState({ editing: true });
|
||||
}
|
||||
};
|
||||
|
||||
stopEditing = () => {
|
||||
const { validate, value, onChange } = this.props;
|
||||
if (validate && !validate(value)) {
|
||||
onChange(this.initialValue);
|
||||
}
|
||||
this.setState({ editing: false });
|
||||
};
|
||||
|
||||
handleBlur = e => {
|
||||
const { onBlur } = this.props;
|
||||
this.stopEditing();
|
||||
if (onBlur) {
|
||||
onBlur(e.target.value);
|
||||
}
|
||||
};
|
||||
|
||||
handleChange = e => this.props.onChange(e.target.value);
|
||||
|
||||
handleKey = e => {
|
||||
if (e.key === 'Enter') {
|
||||
this.handleBlur(e);
|
||||
}
|
||||
};
|
||||
|
||||
handleFocus = e => {
|
||||
const val = e.target.value;
|
||||
e.target.value = '';
|
||||
e.target.value = val;
|
||||
};
|
||||
|
||||
render() {
|
||||
const { children, className, value } = this.props;
|
||||
|
||||
const style = {
|
||||
width: this.state.width,
|
||||
textIndent: this.state.indent,
|
||||
paddingLeft: 0
|
||||
};
|
||||
|
||||
return this.state.editing ? (
|
||||
<input
|
||||
ref={this.inputEl}
|
||||
className={className}
|
||||
type="text"
|
||||
value={value}
|
||||
onBlur={this.handleBlur}
|
||||
onChange={this.handleChange}
|
||||
onKeyDown={this.handleKey}
|
||||
onFocus={this.handleFocus}
|
||||
style={style}
|
||||
spellCheck={false}
|
||||
/>
|
||||
) : (
|
||||
<div onClick={this.startEditing}>{children}</div>
|
||||
);
|
||||
}
|
||||
}
|
48
client/js/components/ui/FileInput.js
Normal file
48
client/js/components/ui/FileInput.js
Normal file
|
@ -0,0 +1,48 @@
|
|||
import React, { PureComponent } from 'react';
|
||||
import Button from 'components/ui/Button';
|
||||
|
||||
export default class FileInput extends PureComponent {
|
||||
static defaultProps = {
|
||||
type: 'text'
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
this.input = window.document.createElement('input');
|
||||
this.input.setAttribute('type', 'file');
|
||||
|
||||
this.input.addEventListener('change', e => {
|
||||
const file = e.target.files[0];
|
||||
const reader = new FileReader();
|
||||
const { onChange, type } = this.props;
|
||||
|
||||
reader.onload = () => {
|
||||
onChange(file.name, reader.result);
|
||||
};
|
||||
|
||||
switch (type) {
|
||||
case 'binary':
|
||||
reader.readAsArrayBuffer(file);
|
||||
break;
|
||||
|
||||
case 'text':
|
||||
reader.readAsText(file);
|
||||
break;
|
||||
|
||||
default:
|
||||
reader.readAsText(file);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
handleClick = () => this.input.click();
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Button className="input-file" onClick={this.handleClick}>
|
||||
{this.props.name}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
}
|
7
client/js/components/ui/Navicon.js
Normal file
7
client/js/components/ui/Navicon.js
Normal file
|
@ -0,0 +1,7 @@
|
|||
import React from 'react';
|
||||
|
||||
const Navicon = ({ onClick }) => (
|
||||
<i className="icon-menu navicon" onClick={onClick} />
|
||||
);
|
||||
|
||||
export default Navicon;
|
87
client/js/components/ui/TextInput.js
Normal file
87
client/js/components/ui/TextInput.js
Normal file
|
@ -0,0 +1,87 @@
|
|||
import React, { PureComponent } from 'react';
|
||||
import { FastField } from 'formik';
|
||||
import classnames from 'classnames';
|
||||
import capitalize from 'lodash/capitalize';
|
||||
import Error from 'components/ui/formik/Error';
|
||||
|
||||
export default class TextInput extends PureComponent {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.input = React.createRef();
|
||||
window.addEventListener('resize', this.handleResize);
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
window.removeEventListener('resize', this.handleResize);
|
||||
}
|
||||
|
||||
handleResize = () => {
|
||||
if (this.scroll) {
|
||||
this.scroll = false;
|
||||
this.scrollIntoView();
|
||||
}
|
||||
};
|
||||
|
||||
handleFocus = () => {
|
||||
this.scroll = true;
|
||||
setTimeout(() => {
|
||||
this.scroll = false;
|
||||
}, 2000);
|
||||
};
|
||||
|
||||
scrollIntoView = () => {
|
||||
if (this.input.current.scrollIntoViewIfNeeded) {
|
||||
this.input.current.scrollIntoViewIfNeeded();
|
||||
} else {
|
||||
this.input.current.scrollIntoView();
|
||||
}
|
||||
};
|
||||
|
||||
render() {
|
||||
const { name, label = capitalize(name), noError, ...props } = this.props;
|
||||
|
||||
return (
|
||||
<FastField
|
||||
name={name}
|
||||
render={({ field, form }) => {
|
||||
return (
|
||||
<>
|
||||
<div className="textinput">
|
||||
<input
|
||||
className={field.value && 'value'}
|
||||
type="text"
|
||||
name={name}
|
||||
autoCapitalize="off"
|
||||
autoCorrect="off"
|
||||
autoComplete="off"
|
||||
spellCheck="false"
|
||||
ref={this.input}
|
||||
onFocus={this.handleFocus}
|
||||
{...field}
|
||||
{...props}
|
||||
/>
|
||||
<span
|
||||
className={classnames('textinput-1', {
|
||||
value: field.value,
|
||||
error: form.touched[name] && form.errors[name]
|
||||
})}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
<span
|
||||
className={classnames('textinput-2', {
|
||||
value: field.value,
|
||||
error: form.touched[name] && form.errors[name]
|
||||
})}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
{!noError && <Error name={name} />}
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
27
client/js/components/ui/formik/Checkbox.js
Normal file
27
client/js/components/ui/formik/Checkbox.js
Normal file
|
@ -0,0 +1,27 @@
|
|||
import React, { memo } from 'react';
|
||||
import { FastField } from 'formik';
|
||||
import Checkbox from 'components/ui/Checkbox';
|
||||
|
||||
const FormikCheckbox = ({ name, onChange, ...props }) => (
|
||||
<FastField
|
||||
name={name}
|
||||
render={({ field, form }) => {
|
||||
return (
|
||||
<Checkbox
|
||||
name={name}
|
||||
checked={field.value}
|
||||
onChange={e => {
|
||||
form.setFieldTouched(name, true);
|
||||
field.onChange(e);
|
||||
if (onChange) {
|
||||
onChange(e);
|
||||
}
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
export default memo(FormikCheckbox);
|
8
client/js/components/ui/formik/Error.js
Normal file
8
client/js/components/ui/formik/Error.js
Normal file
|
@ -0,0 +1,8 @@
|
|||
import React from 'react';
|
||||
import { ErrorMessage } from 'formik';
|
||||
|
||||
const Error = props => (
|
||||
<ErrorMessage component="div" className="form-error" {...props} />
|
||||
);
|
||||
|
||||
export default Error;
|
0
client/js/components/ui/formik/TextInput.js
Normal file
0
client/js/components/ui/formik/TextInput.js
Normal file
27
client/js/containers/App.js
Normal file
27
client/js/containers/App.js
Normal file
|
@ -0,0 +1,27 @@
|
|||
import { createStructuredSelector } from 'reselect';
|
||||
import App from 'components/App';
|
||||
import { getConnected } from 'state/app';
|
||||
import { getSortedChannels } from 'state/channels';
|
||||
import { getPrivateChats } from 'state/privateChats';
|
||||
import { getServers } from 'state/servers';
|
||||
import { getSelectedTab, select } from 'state/tab';
|
||||
import { getShowTabList, hideMenu } from 'state/ui';
|
||||
import connect from 'utils/connect';
|
||||
import { push } from 'utils/router';
|
||||
|
||||
const mapState = createStructuredSelector({
|
||||
channels: getSortedChannels,
|
||||
connected: getConnected,
|
||||
privateChats: getPrivateChats,
|
||||
servers: getServers,
|
||||
showTabList: getShowTabList,
|
||||
tab: getSelectedTab,
|
||||
newVersionAvailable: state => state.app.newVersionAvailable
|
||||
});
|
||||
|
||||
const mapDispatch = { push, select, hideMenu };
|
||||
|
||||
export default connect(
|
||||
mapState,
|
||||
mapDispatch
|
||||
)(App);
|
89
client/js/containers/Chat.js
Normal file
89
client/js/containers/Chat.js
Normal file
|
@ -0,0 +1,89 @@
|
|||
import { bindActionCreators } from 'redux';
|
||||
import { createStructuredSelector } from 'reselect';
|
||||
import Chat from 'components/pages/Chat';
|
||||
import { getSelectedTabTitle } from 'state';
|
||||
import {
|
||||
getSelectedChannel,
|
||||
getSelectedChannelUsers,
|
||||
part
|
||||
} from 'state/channels';
|
||||
import {
|
||||
getCurrentInputHistoryEntry,
|
||||
addInputHistory,
|
||||
resetInputHistory,
|
||||
incrementInputHistory,
|
||||
decrementInputHistory
|
||||
} from 'state/input';
|
||||
import {
|
||||
getSelectedMessages,
|
||||
getHasMoreMessages,
|
||||
runCommand,
|
||||
sendMessage,
|
||||
fetchMessages,
|
||||
addFetchedMessages
|
||||
} from 'state/messages';
|
||||
import { openPrivateChat, closePrivateChat } from 'state/privateChats';
|
||||
import { getSearch, searchMessages, toggleSearch } from 'state/search';
|
||||
import {
|
||||
getCurrentNick,
|
||||
getCurrentServerStatus,
|
||||
disconnect,
|
||||
setNick,
|
||||
setServerName
|
||||
} from 'state/servers';
|
||||
import { getSettings } from 'state/settings';
|
||||
import { getSelectedTab, select } from 'state/tab';
|
||||
import { getShowUserList, toggleUserList } from 'state/ui';
|
||||
import connect from 'utils/connect';
|
||||
|
||||
const mapState = createStructuredSelector({
|
||||
channel: getSelectedChannel,
|
||||
currentInputHistoryEntry: getCurrentInputHistoryEntry,
|
||||
hasMoreMessages: getHasMoreMessages,
|
||||
messages: getSelectedMessages,
|
||||
nick: getCurrentNick,
|
||||
search: getSearch,
|
||||
showUserList: getShowUserList,
|
||||
status: getCurrentServerStatus,
|
||||
tab: getSelectedTab,
|
||||
title: getSelectedTabTitle,
|
||||
users: getSelectedChannelUsers,
|
||||
coloredNicks: state => getSettings(state).coloredNicks
|
||||
});
|
||||
|
||||
const mapDispatch = dispatch => ({
|
||||
...bindActionCreators(
|
||||
{
|
||||
addFetchedMessages,
|
||||
closePrivateChat,
|
||||
disconnect,
|
||||
fetchMessages,
|
||||
openPrivateChat,
|
||||
part,
|
||||
runCommand,
|
||||
searchMessages,
|
||||
select,
|
||||
sendMessage,
|
||||
setNick,
|
||||
setServerName,
|
||||
toggleSearch,
|
||||
toggleUserList
|
||||
},
|
||||
dispatch
|
||||
),
|
||||
|
||||
inputActions: bindActionCreators(
|
||||
{
|
||||
add: addInputHistory,
|
||||
reset: resetInputHistory,
|
||||
increment: incrementInputHistory,
|
||||
decrement: decrementInputHistory
|
||||
},
|
||||
dispatch
|
||||
)
|
||||
});
|
||||
|
||||
export default connect(
|
||||
mapState,
|
||||
mapDispatch
|
||||
)(Chat);
|
23
client/js/containers/Connect.js
Normal file
23
client/js/containers/Connect.js
Normal file
|
@ -0,0 +1,23 @@
|
|||
import { createStructuredSelector } from 'reselect';
|
||||
import Connect from 'components/pages/Connect';
|
||||
import { getConnectDefaults, getApp } from 'state/app';
|
||||
import { join } from 'state/channels';
|
||||
import { connect as connectServer } from 'state/servers';
|
||||
import { select } from 'state/tab';
|
||||
import connect from 'utils/connect';
|
||||
|
||||
const mapState = createStructuredSelector({
|
||||
defaults: getConnectDefaults,
|
||||
hexIP: state => getApp(state).hexIP
|
||||
});
|
||||
|
||||
const mapDispatch = {
|
||||
join,
|
||||
connect: connectServer,
|
||||
select
|
||||
};
|
||||
|
||||
export default connect(
|
||||
mapState,
|
||||
mapDispatch
|
||||
)(Connect);
|
12
client/js/containers/Navicon.js
Normal file
12
client/js/containers/Navicon.js
Normal file
|
@ -0,0 +1,12 @@
|
|||
import Navicon from 'components/ui/Navicon';
|
||||
import { toggleMenu } from 'state/ui';
|
||||
import connect from 'utils/connect';
|
||||
|
||||
const mapDispatch = {
|
||||
onClick: toggleMenu
|
||||
};
|
||||
|
||||
export default connect(
|
||||
null,
|
||||
mapDispatch
|
||||
)(Navicon);
|
17
client/js/containers/Route.js
Normal file
17
client/js/containers/Route.js
Normal file
|
@ -0,0 +1,17 @@
|
|||
import { createStructuredSelector } from 'reselect';
|
||||
import connect from 'utils/connect';
|
||||
|
||||
const Route = ({ route, name, children }) => {
|
||||
if (route === name) {
|
||||
return children;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const getRoute = state => state.router.route;
|
||||
|
||||
const mapState = createStructuredSelector({
|
||||
route: getRoute
|
||||
});
|
||||
|
||||
export default connect(mapState)(Route);
|
29
client/js/containers/Settings.js
Normal file
29
client/js/containers/Settings.js
Normal file
|
@ -0,0 +1,29 @@
|
|||
import { createStructuredSelector } from 'reselect';
|
||||
import Settings from 'components/pages/Settings';
|
||||
import { appSet } from 'state/app';
|
||||
import {
|
||||
getSettings,
|
||||
setSetting,
|
||||
setCert,
|
||||
setKey,
|
||||
uploadCert
|
||||
} from 'state/settings';
|
||||
import connect from 'utils/connect';
|
||||
|
||||
const mapState = createStructuredSelector({
|
||||
settings: getSettings,
|
||||
installable: state => state.app.installable
|
||||
});
|
||||
|
||||
const mapDispatch = {
|
||||
onCertChange: setCert,
|
||||
onKeyChange: setKey,
|
||||
uploadCert,
|
||||
setSetting,
|
||||
onInstall: () => appSet('installable', null)
|
||||
};
|
||||
|
||||
export default connect(
|
||||
mapState,
|
||||
mapDispatch
|
||||
)(Settings);
|
35
client/js/index.js
Normal file
35
client/js/index.js
Normal file
|
@ -0,0 +1,35 @@
|
|||
import React from 'react';
|
||||
import { createRoot } from 'react-dom';
|
||||
|
||||
import Root from 'components/Root';
|
||||
import { appSet } from 'state/app';
|
||||
import initRouter from 'utils/router';
|
||||
import Socket from 'utils/Socket';
|
||||
import configureStore from './store';
|
||||
import routes from './routes';
|
||||
import runModules from './modules';
|
||||
import { register } from './serviceWorker';
|
||||
import '../css/fonts.css';
|
||||
import '../css/fontello.css';
|
||||
import '../css/style.css';
|
||||
|
||||
const production = process.env.NODE_ENV === 'production';
|
||||
const host = production
|
||||
? window.location.host
|
||||
: `${window.location.hostname}:1337`;
|
||||
const socket = new Socket(host);
|
||||
const store = configureStore(socket);
|
||||
|
||||
initRouter(routes, store);
|
||||
runModules({ store, socket });
|
||||
|
||||
createRoot(document.getElementById('root')).render(<Root store={store} />);
|
||||
|
||||
window.addEventListener('beforeinstallprompt', e => {
|
||||
e.preventDefault();
|
||||
store.dispatch(appSet('installable', e));
|
||||
});
|
||||
|
||||
register({
|
||||
onUpdate: () => store.dispatch(appSet('newVersionAvailable', true))
|
||||
});
|
47
client/js/middleware/command.js
Normal file
47
client/js/middleware/command.js
Normal file
|
@ -0,0 +1,47 @@
|
|||
import { addMessages, inform, print } from 'state/messages';
|
||||
import { isChannel } from 'utils';
|
||||
|
||||
export const beforeHandler = '_before';
|
||||
export const notFoundHandler = 'commandNotFound';
|
||||
|
||||
function createContext({ dispatch, getState }, { server, channel }) {
|
||||
return { dispatch, getState, server, channel, isChannel: isChannel(channel) };
|
||||
}
|
||||
|
||||
// TODO: Pull this out as convenience action
|
||||
function process({ dispatch, server, channel }, result) {
|
||||
if (typeof result === 'string') {
|
||||
dispatch(inform(result, server, channel));
|
||||
} else if (Array.isArray(result)) {
|
||||
if (typeof result[0] === 'string') {
|
||||
dispatch(inform(result, server, channel));
|
||||
} else if (typeof result[0] === 'object') {
|
||||
dispatch(addMessages(result, server, channel));
|
||||
}
|
||||
} else if (typeof result === 'object' && result) {
|
||||
dispatch(print(result.content, server, channel, result.type));
|
||||
}
|
||||
}
|
||||
|
||||
export default function createCommandMiddleware(type, handlers) {
|
||||
return store => next => action => {
|
||||
if (action.type === type) {
|
||||
const words = action.command.slice(1).split(' ');
|
||||
const command = words[0];
|
||||
const params = words.slice(1);
|
||||
|
||||
if (command in handlers) {
|
||||
const ctx = createContext(store, action);
|
||||
if (beforeHandler in handlers) {
|
||||
process(ctx, handlers[beforeHandler](ctx, command, ...params));
|
||||
}
|
||||
process(ctx, handlers[command](ctx, ...params));
|
||||
} else if (notFoundHandler in handlers) {
|
||||
const ctx = createContext(store, action);
|
||||
process(ctx, handlers[notFoundHandler](ctx, command, ...params));
|
||||
}
|
||||
}
|
||||
|
||||
return next(action);
|
||||
};
|
||||
}
|
35
client/js/middleware/message.js
Normal file
35
client/js/middleware/message.js
Normal file
|
@ -0,0 +1,35 @@
|
|||
import { ADD_MESSAGES, ADD_FETCHED_MESSAGES } from 'state/actions';
|
||||
|
||||
//
|
||||
// This middleware handles waiting until MessageBox
|
||||
// is ready before adding messages to the top
|
||||
//
|
||||
const message = store => next => {
|
||||
const ready = {};
|
||||
const cache = {};
|
||||
|
||||
return action => {
|
||||
if (action.type === ADD_MESSAGES && action.prepend) {
|
||||
const key = `${action.server} ${action.channel}`;
|
||||
|
||||
if (ready[key]) {
|
||||
ready[key] = false;
|
||||
return next(action);
|
||||
}
|
||||
|
||||
cache[key] = action;
|
||||
} else if (action.type === ADD_FETCHED_MESSAGES) {
|
||||
const key = `${action.server} ${action.channel}`;
|
||||
ready[key] = true;
|
||||
|
||||
if (cache[key]) {
|
||||
store.dispatch(cache[key]);
|
||||
cache[key] = undefined;
|
||||
}
|
||||
} else {
|
||||
return next(action);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export default message;
|
36
client/js/middleware/socket.js
Normal file
36
client/js/middleware/socket.js
Normal file
|
@ -0,0 +1,36 @@
|
|||
import debounce from 'lodash/debounce';
|
||||
|
||||
const debounceKey = action => {
|
||||
const { key } = action.socket.debounce;
|
||||
if (key) {
|
||||
return `${action.type} ${key}`;
|
||||
}
|
||||
return action.type;
|
||||
};
|
||||
|
||||
export default function createSocketMiddleware(socket) {
|
||||
return () => next => {
|
||||
const debounced = {};
|
||||
|
||||
return action => {
|
||||
if (action.socket) {
|
||||
if (action.socket.debounce) {
|
||||
const key = debounceKey(action);
|
||||
|
||||
if (!debounced[key]) {
|
||||
debounced[key] = debounce((type, data) => {
|
||||
socket.send(type, data);
|
||||
debounced[key] = undefined;
|
||||
}, action.socket.debounce.delay);
|
||||
}
|
||||
|
||||
debounced[key](action.socket.type, action.socket.data);
|
||||
} else {
|
||||
socket.send(action.socket.type, action.socket.data);
|
||||
}
|
||||
}
|
||||
|
||||
return next(action);
|
||||
};
|
||||
};
|
||||
}
|
23
client/js/modules/documentTitle.js
Normal file
23
client/js/modules/documentTitle.js
Normal file
|
@ -0,0 +1,23 @@
|
|||
import capitalize from 'lodash/capitalize';
|
||||
import { getRouter } from 'state';
|
||||
import { getCurrentServerName } from 'state/servers';
|
||||
import { observe } from 'utils/observe';
|
||||
|
||||
export default function documentTitle({ store }) {
|
||||
observe(store, [getRouter, getCurrentServerName], (router, serverName) => {
|
||||
let title;
|
||||
|
||||
if (router.route === 'chat') {
|
||||
const { name } = router.params;
|
||||
if (name) {
|
||||
title = `${name} @ ${serverName}`;
|
||||
} else {
|
||||
title = serverName;
|
||||
}
|
||||
} else {
|
||||
title = capitalize(router.route);
|
||||
}
|
||||
|
||||
document.title = `${title} | Dispatch`;
|
||||
});
|
||||
}
|
22
client/js/modules/fonts.js
Normal file
22
client/js/modules/fonts.js
Normal file
|
@ -0,0 +1,22 @@
|
|||
import FontFaceObserver from 'fontfaceobserver';
|
||||
import { setCharWidth } from 'state/app';
|
||||
import { stringWidth } from 'utils';
|
||||
|
||||
export default function fonts({ store }) {
|
||||
let { charWidth } = localStorage;
|
||||
if (charWidth) {
|
||||
store.dispatch(setCharWidth(parseFloat(charWidth)));
|
||||
}
|
||||
|
||||
new FontFaceObserver('Roboto Mono').load().then(() => {
|
||||
if (!charWidth) {
|
||||
charWidth = stringWidth(' ', '16px Roboto Mono');
|
||||
store.dispatch(setCharWidth(charWidth));
|
||||
localStorage.charWidth = charWidth;
|
||||
}
|
||||
});
|
||||
|
||||
new FontFaceObserver('Montserrat').load();
|
||||
new FontFaceObserver('Montserrat', { weight: 700 }).load();
|
||||
new FontFaceObserver('Roboto Mono', { weight: 700 }).load();
|
||||
}
|
16
client/js/modules/index.js
Normal file
16
client/js/modules/index.js
Normal file
|
@ -0,0 +1,16 @@
|
|||
import documentTitle from './documentTitle';
|
||||
import fonts from './fonts';
|
||||
import initialState from './initialState';
|
||||
import socket from './socket';
|
||||
import storage from './storage';
|
||||
import widthUpdates from './widthUpdates';
|
||||
|
||||
export default function runModules(ctx) {
|
||||
fonts(ctx);
|
||||
initialState(ctx);
|
||||
|
||||
documentTitle(ctx);
|
||||
socket(ctx);
|
||||
storage(ctx);
|
||||
widthUpdates(ctx);
|
||||
}
|
80
client/js/modules/initialState.js
Normal file
80
client/js/modules/initialState.js
Normal file
|
@ -0,0 +1,80 @@
|
|||
/* eslint-disable no-underscore-dangle */
|
||||
import Cookie from 'js-cookie';
|
||||
import { socket as socketActions } from 'state/actions';
|
||||
import { getWrapWidth, setConnectDefaults, appSet } from 'state/app';
|
||||
import { addMessages } from 'state/messages';
|
||||
import { setSettings } from 'state/settings';
|
||||
import { select, updateSelection } from 'state/tab';
|
||||
import { find } from 'utils';
|
||||
import { when } from 'utils/observe';
|
||||
import { replace } from 'utils/router';
|
||||
|
||||
function loadState({ store }, env) {
|
||||
store.dispatch(setConnectDefaults(env.defaults));
|
||||
store.dispatch(appSet('hexIP', env.hexIP));
|
||||
store.dispatch(setSettings(env.settings, true));
|
||||
|
||||
if (env.servers) {
|
||||
store.dispatch({
|
||||
type: socketActions.SERVERS,
|
||||
data: env.servers
|
||||
});
|
||||
|
||||
if (!store.getState().router.route) {
|
||||
const tab = Cookie.get('tab');
|
||||
if (tab) {
|
||||
const [server, name = null] = tab.split(/;(.+)/);
|
||||
|
||||
if (
|
||||
name &&
|
||||
find(
|
||||
env.channels,
|
||||
chan => chan.server === server && chan.name === name
|
||||
)
|
||||
) {
|
||||
store.dispatch(select(server, name, true));
|
||||
} else if (find(env.servers, srv => srv.host === server)) {
|
||||
store.dispatch(select(server, null, true));
|
||||
} else {
|
||||
store.dispatch(updateSelection());
|
||||
}
|
||||
} else {
|
||||
store.dispatch(updateSelection());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
store.dispatch(replace('/connect'));
|
||||
}
|
||||
|
||||
if (env.channels) {
|
||||
store.dispatch({
|
||||
type: socketActions.CHANNELS,
|
||||
data: env.channels
|
||||
});
|
||||
}
|
||||
|
||||
if (env.users) {
|
||||
store.dispatch({
|
||||
type: socketActions.USERS,
|
||||
...env.users
|
||||
});
|
||||
}
|
||||
|
||||
// Wait until wrapWidth gets initialized so that height calculations
|
||||
// only happen once for these messages
|
||||
when(store, getWrapWidth, () => {
|
||||
if (env.messages) {
|
||||
const { messages, server, to, next } = env.messages;
|
||||
store.dispatch(addMessages(messages, server, to, false, next));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export default function initialState(ctx) {
|
||||
if (window.__env__) {
|
||||
window.__env__.then(env => loadState(ctx, env));
|
||||
} else {
|
||||
const env = JSON.parse(document.getElementById('env').innerHTML);
|
||||
loadState(ctx, env);
|
||||
}
|
||||
}
|
161
client/js/modules/socket.js
Normal file
161
client/js/modules/socket.js
Normal file
|
@ -0,0 +1,161 @@
|
|||
import { socketAction } from 'state/actions';
|
||||
import { setConnected } from 'state/app';
|
||||
import {
|
||||
broadcast,
|
||||
inform,
|
||||
print,
|
||||
addMessage,
|
||||
addMessages
|
||||
} from 'state/messages';
|
||||
import { reconnect } from 'state/servers';
|
||||
import { select } from 'state/tab';
|
||||
import { find, normalizeChannel } from 'utils';
|
||||
|
||||
function withReason(message, reason) {
|
||||
return message + (reason ? ` (${reason})` : '');
|
||||
}
|
||||
|
||||
function findChannels(state, server, user) {
|
||||
const channels = [];
|
||||
|
||||
Object.keys(state.channels[server]).forEach(channel => {
|
||||
if (find(state.channels[server][channel].users, u => u.nick === user)) {
|
||||
channels.push(channel);
|
||||
}
|
||||
});
|
||||
|
||||
return channels;
|
||||
}
|
||||
|
||||
export default function handleSocket({
|
||||
socket,
|
||||
store: { dispatch, getState }
|
||||
}) {
|
||||
const handlers = {
|
||||
message(message) {
|
||||
dispatch(addMessage(message, message.server, message.to));
|
||||
},
|
||||
|
||||
pm(message) {
|
||||
dispatch(addMessage(message, message.server, message.from));
|
||||
},
|
||||
|
||||
messages({ messages, server, to, prepend, next }) {
|
||||
dispatch(addMessages(messages, server, to, prepend, next));
|
||||
},
|
||||
|
||||
join({ user, server, channels }) {
|
||||
const state = getState();
|
||||
const tab = state.tab.selected;
|
||||
const [joinedChannel] = channels;
|
||||
if (tab.server && tab.name) {
|
||||
const { nick } = state.servers[tab.server];
|
||||
if (
|
||||
tab.server === server &&
|
||||
nick === user &&
|
||||
tab.name !== joinedChannel &&
|
||||
normalizeChannel(tab.name) === normalizeChannel(joinedChannel)
|
||||
) {
|
||||
dispatch(select(server, joinedChannel));
|
||||
}
|
||||
}
|
||||
|
||||
dispatch(inform(`${user} joined the channel`, server, joinedChannel));
|
||||
},
|
||||
|
||||
part({ user, server, channel, reason }) {
|
||||
dispatch(
|
||||
inform(withReason(`${user} left the channel`, reason), server, channel)
|
||||
);
|
||||
},
|
||||
|
||||
quit({ user, server, reason }) {
|
||||
const channels = findChannels(getState(), server, user);
|
||||
dispatch(broadcast(withReason(`${user} quit`, reason), server, channels));
|
||||
},
|
||||
|
||||
nick({ server, oldNick, newNick }) {
|
||||
const channels = findChannels(getState(), server, oldNick);
|
||||
dispatch(
|
||||
broadcast(`${oldNick} changed nick to ${newNick}`, server, channels)
|
||||
);
|
||||
},
|
||||
|
||||
topic({ server, channel, topic, nick }) {
|
||||
if (nick) {
|
||||
if (topic) {
|
||||
dispatch(inform(`${nick} changed the topic to:`, server, channel));
|
||||
dispatch(print(topic, server, channel));
|
||||
} else {
|
||||
dispatch(inform(`${nick} cleared the topic`, server, channel));
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
motd({ content, server }) {
|
||||
dispatch(addMessages(content.map(line => ({ content: line })), server));
|
||||
},
|
||||
|
||||
whois(data) {
|
||||
const tab = getState().tab.selected;
|
||||
|
||||
dispatch(
|
||||
print(
|
||||
[
|
||||
`Nick: ${data.nick}`,
|
||||
`Username: ${data.username}`,
|
||||
`Realname: ${data.realname}`,
|
||||
`Host: ${data.host}`,
|
||||
`Server: ${data.server}`,
|
||||
`Channels: ${data.channels}`
|
||||
],
|
||||
tab.server,
|
||||
tab.name
|
||||
)
|
||||
);
|
||||
},
|
||||
|
||||
print(message) {
|
||||
const tab = getState().tab.selected;
|
||||
dispatch(addMessage(message, tab.server, tab.name));
|
||||
},
|
||||
|
||||
connection_update({ server, errorType }) {
|
||||
if (
|
||||
errorType === 'verify' &&
|
||||
window.confirm(
|
||||
'The server is using a self-signed certificate, continue anyway?'
|
||||
)
|
||||
) {
|
||||
dispatch(
|
||||
reconnect(server, {
|
||||
skipVerify: true
|
||||
})
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
_connected(connected) {
|
||||
dispatch(setConnected(connected));
|
||||
}
|
||||
};
|
||||
|
||||
socket.onMessage((type, data) => {
|
||||
let action;
|
||||
if (Array.isArray(data)) {
|
||||
action = { type: socketAction(type), data: [...data] };
|
||||
} else {
|
||||
action = { ...data, type: socketAction(type) };
|
||||
}
|
||||
|
||||
if (type in handlers) {
|
||||
handlers[type](data);
|
||||
}
|
||||
|
||||
if (type.charAt(0) === '_') {
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch(action);
|
||||
});
|
||||
}
|
18
client/js/modules/storage.js
Normal file
18
client/js/modules/storage.js
Normal file
|
@ -0,0 +1,18 @@
|
|||
import Cookie from 'js-cookie';
|
||||
import debounce from 'lodash/debounce';
|
||||
import { getSelectedTab } from 'state/tab';
|
||||
import { isChannel, stringifyTab } from 'utils';
|
||||
import { observe } from 'utils/observe';
|
||||
|
||||
const saveTab = debounce(
|
||||
tab => Cookie.set('tab', stringifyTab(tab), { expires: 30 }),
|
||||
1000
|
||||
);
|
||||
|
||||
export default function storage({ store }) {
|
||||
observe(store, getSelectedTab, tab => {
|
||||
if (isChannel(tab) || (tab.server && !tab.name)) {
|
||||
saveTab(tab);
|
||||
}
|
||||
});
|
||||
}
|
31
client/js/modules/widthUpdates.js
Normal file
31
client/js/modules/widthUpdates.js
Normal file
|
@ -0,0 +1,31 @@
|
|||
import { getCharWidth } from 'state/app';
|
||||
import { updateMessageHeight } from 'state/messages';
|
||||
import { when } from 'utils/observe';
|
||||
import { measureScrollBarWidth } from 'utils';
|
||||
import { addResizeListener } from 'utils/size';
|
||||
|
||||
const menuWidth = 200;
|
||||
const messagePadding = 30;
|
||||
const smallScreen = 600;
|
||||
|
||||
export default function widthUpdates({ store }) {
|
||||
when(store, getCharWidth, charWidth => {
|
||||
window.messageIndent = 6 * charWidth;
|
||||
const scrollBarWidth = measureScrollBarWidth();
|
||||
let prevWrapWidth;
|
||||
|
||||
function updateWidth(windowWidth) {
|
||||
let wrapWidth = windowWidth - scrollBarWidth - messagePadding;
|
||||
if (windowWidth > smallScreen) {
|
||||
wrapWidth -= menuWidth;
|
||||
}
|
||||
|
||||
if (wrapWidth !== prevWrapWidth) {
|
||||
prevWrapWidth = wrapWidth;
|
||||
store.dispatch(updateMessageHeight(wrapWidth, charWidth, windowWidth));
|
||||
}
|
||||
}
|
||||
|
||||
addResizeListener(updateWidth, true);
|
||||
});
|
||||
}
|
5
client/js/routes.js
Normal file
5
client/js/routes.js
Normal file
|
@ -0,0 +1,5 @@
|
|||
export default {
|
||||
connect: '/connect',
|
||||
settings: '/settings',
|
||||
chat: '/:server(/:name)'
|
||||
};
|
90
client/js/serviceWorker.js
Normal file
90
client/js/serviceWorker.js
Normal file
|
@ -0,0 +1,90 @@
|
|||
const isLocalhost = Boolean(
|
||||
window.location.hostname === 'localhost' ||
|
||||
// [::1] is the IPv6 localhost address.
|
||||
window.location.hostname === '[::1]' ||
|
||||
// 127.0.0.1/8 is considered localhost for IPv4.
|
||||
window.location.hostname.match(
|
||||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
||||
)
|
||||
);
|
||||
|
||||
function registerValidSW(swUrl, config) {
|
||||
navigator.serviceWorker
|
||||
.register(swUrl)
|
||||
.then(registration => {
|
||||
registration.onupdatefound = () => {
|
||||
const installingWorker = registration.installing;
|
||||
if (installingWorker == null) {
|
||||
return;
|
||||
}
|
||||
installingWorker.onstatechange = () => {
|
||||
if (installingWorker.state === 'installed') {
|
||||
if (navigator.serviceWorker.controller) {
|
||||
if (config && config.onUpdate) {
|
||||
config.onUpdate(registration);
|
||||
}
|
||||
} else {
|
||||
if (config && config.onSuccess) {
|
||||
config.onSuccess(registration);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error during service worker registration:', error);
|
||||
});
|
||||
}
|
||||
|
||||
function checkValidServiceWorker(swUrl, config) {
|
||||
// Check if the service worker can be found. If it can't reload the page.
|
||||
fetch(swUrl)
|
||||
.then(response => {
|
||||
// Ensure service worker exists, and that we really are getting a JS file.
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (
|
||||
response.status === 404 ||
|
||||
(contentType != null && contentType.indexOf('javascript') === -1)
|
||||
) {
|
||||
// No service worker found. Probably a different app. Reload the page.
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister().then(() => {
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
} else {
|
||||
// Service worker found. Proceed as normal.
|
||||
registerValidSW(swUrl, config);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
console.log(
|
||||
'No internet connection found. App is running in offline mode.'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function register(config) {
|
||||
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
||||
window.addEventListener('load', () => {
|
||||
const swUrl = '/sw.js';
|
||||
|
||||
if (isLocalhost) {
|
||||
// This is running on localhost. Let's check if a service worker still exists or not.
|
||||
checkValidServiceWorker(swUrl, config);
|
||||
} else {
|
||||
// Is not localhost. Just register service worker
|
||||
registerValidSW(swUrl, config);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function unregister() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister();
|
||||
});
|
||||
}
|
||||
}
|
20
client/js/state/__tests__/actions-servers.test.js
Normal file
20
client/js/state/__tests__/actions-servers.test.js
Normal file
|
@ -0,0 +1,20 @@
|
|||
import { connect, setServerName } from '../servers';
|
||||
|
||||
describe('setServerName()', () => {
|
||||
it('passes valid names to the server', () => {
|
||||
const name = 'cake';
|
||||
const server = 'srv';
|
||||
|
||||
expect(setServerName(name, server)).toMatchObject({
|
||||
socket: {
|
||||
type: 'set_server_name',
|
||||
data: { name, server }
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('does not pass invalid names to the server', () => {
|
||||
expect(setServerName('', 'srv').socket).toBeUndefined();
|
||||
expect(setServerName(' ', 'srv').socket).toBeUndefined();
|
||||
});
|
||||
});
|
335
client/js/state/__tests__/reducer-channels.test.js
Normal file
335
client/js/state/__tests__/reducer-channels.test.js
Normal file
|
@ -0,0 +1,335 @@
|
|||
import reducer, { compareUsers, getSortedChannels } from '../channels';
|
||||
import { connect } from '../servers';
|
||||
import * as actions from '../actions';
|
||||
|
||||
describe('channel reducer', () => {
|
||||
it('removes channels on PART', () => {
|
||||
let state = {
|
||||
srv1: {
|
||||
chan1: {},
|
||||
chan2: {},
|
||||
chan3: {}
|
||||
},
|
||||
srv2: {
|
||||
chan1: {}
|
||||
}
|
||||
};
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.PART,
|
||||
server: 'srv1',
|
||||
channels: ['chan1', 'chan3']
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
srv1: {
|
||||
chan2: {}
|
||||
},
|
||||
srv2: {
|
||||
chan1: {}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('handles SOCKET_PART', () => {
|
||||
let state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
|
||||
state = reducer(state, socket_join('srv', 'chan1', 'nick2'));
|
||||
state = reducer(state, socket_join('srv', 'chan2', 'nick2'));
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.socket.PART,
|
||||
server: 'srv',
|
||||
channel: 'chan1',
|
||||
user: 'nick2'
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {
|
||||
chan1: {
|
||||
users: [{ mode: '', nick: 'nick1', renderName: 'nick1' }]
|
||||
},
|
||||
chan2: {
|
||||
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('handles SOCKET_JOIN', () => {
|
||||
const state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {
|
||||
chan1: {
|
||||
users: [{ mode: '', nick: 'nick1', renderName: 'nick1' }]
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('handles SOCKET_QUIT', () => {
|
||||
let state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
|
||||
state = reducer(state, socket_join('srv', 'chan1', 'nick2'));
|
||||
state = reducer(state, socket_join('srv', 'chan2', 'nick2'));
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.socket.QUIT,
|
||||
server: 'srv',
|
||||
user: 'nick2'
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {
|
||||
chan1: {
|
||||
users: [{ mode: '', nick: 'nick1', renderName: 'nick1' }]
|
||||
},
|
||||
chan2: {
|
||||
users: []
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('handles SOCKET_NICK', () => {
|
||||
let state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
|
||||
state = reducer(state, socket_join('srv', 'chan1', 'nick2'));
|
||||
state = reducer(state, socket_join('srv', 'chan2', 'nick2'));
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.socket.NICK,
|
||||
server: 'srv',
|
||||
oldNick: 'nick1',
|
||||
newNick: 'nick3'
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {
|
||||
chan1: {
|
||||
users: [
|
||||
{ mode: '', nick: 'nick3', renderName: 'nick3' },
|
||||
{ mode: '', nick: 'nick2', renderName: 'nick2' }
|
||||
]
|
||||
},
|
||||
chan2: {
|
||||
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('handles SOCKET_USERS', () => {
|
||||
const state = reducer(undefined, {
|
||||
type: actions.socket.USERS,
|
||||
server: 'srv',
|
||||
channel: 'chan1',
|
||||
users: ['user3', 'user2', '@user4', 'user1', '+user5']
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {
|
||||
chan1: {
|
||||
users: [
|
||||
{ mode: '', nick: 'user3', renderName: 'user3' },
|
||||
{ mode: '', nick: 'user2', renderName: 'user2' },
|
||||
{ mode: 'o', nick: 'user4', renderName: '@user4' },
|
||||
{ mode: '', nick: 'user1', renderName: 'user1' },
|
||||
{ mode: 'v', nick: 'user5', renderName: '+user5' }
|
||||
]
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('handles SOCKET_TOPIC', () => {
|
||||
const state = reducer(undefined, {
|
||||
type: actions.socket.TOPIC,
|
||||
server: 'srv',
|
||||
channel: 'chan1',
|
||||
topic: 'the topic'
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {
|
||||
chan1: {
|
||||
topic: 'the topic',
|
||||
users: []
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('handles SOCKET_MODE', () => {
|
||||
let state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
|
||||
state = reducer(state, socket_join('srv', 'chan1', 'nick2'));
|
||||
state = reducer(state, socket_join('srv', 'chan2', 'nick2'));
|
||||
|
||||
state = reducer(state, socket_mode('srv', 'chan1', 'nick1', 'o', ''));
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {
|
||||
chan1: {
|
||||
users: [
|
||||
{ mode: 'o', nick: 'nick1', renderName: '@nick1' },
|
||||
{ mode: '', nick: 'nick2', renderName: 'nick2' }
|
||||
]
|
||||
},
|
||||
chan2: {
|
||||
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
state = reducer(state, socket_mode('srv', 'chan1', 'nick1', 'v', 'o'));
|
||||
state = reducer(state, socket_mode('srv', 'chan1', 'nick2', 'o', ''));
|
||||
state = reducer(state, socket_mode('srv', 'chan2', 'not_there', 'x', ''));
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {
|
||||
chan1: {
|
||||
users: [
|
||||
{ mode: 'v', nick: 'nick1', renderName: '+nick1' },
|
||||
{ mode: 'o', nick: 'nick2', renderName: '@nick2' }
|
||||
]
|
||||
},
|
||||
chan2: {
|
||||
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('handles SOCKET_CHANNELS', () => {
|
||||
const state = reducer(undefined, {
|
||||
type: actions.socket.CHANNELS,
|
||||
data: [
|
||||
{ server: 'srv', name: 'chan1', topic: 'the topic' },
|
||||
{ server: 'srv', name: 'chan2' },
|
||||
{ server: 'srv2', name: 'chan1' }
|
||||
]
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {
|
||||
chan1: { topic: 'the topic', users: [] },
|
||||
chan2: { users: [] }
|
||||
},
|
||||
srv2: {
|
||||
chan1: { users: [] }
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('handles SOCKET_SERVERS', () => {
|
||||
const state = reducer(undefined, {
|
||||
type: actions.socket.SERVERS,
|
||||
data: [{ host: '127.0.0.1' }, { host: 'thehost' }]
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
'127.0.0.1': {},
|
||||
thehost: {}
|
||||
});
|
||||
});
|
||||
|
||||
it('optimistically adds the server on CONNECT', () => {
|
||||
const state = reducer(
|
||||
undefined,
|
||||
connect({ host: '127.0.0.1', nick: 'nick' })
|
||||
);
|
||||
|
||||
expect(state).toEqual({
|
||||
'127.0.0.1': {}
|
||||
});
|
||||
});
|
||||
|
||||
it('removes the server on DISCONNECT', () => {
|
||||
let state = {
|
||||
srv: {},
|
||||
srv2: {}
|
||||
};
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.DISCONNECT,
|
||||
server: 'srv2'
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function socket_join(server, channel, user) {
|
||||
return {
|
||||
type: actions.socket.JOIN,
|
||||
server,
|
||||
user,
|
||||
channels: [channel]
|
||||
};
|
||||
}
|
||||
|
||||
function socket_mode(server, channel, user, add, remove) {
|
||||
return {
|
||||
type: actions.socket.MODE,
|
||||
server,
|
||||
channel,
|
||||
user,
|
||||
add,
|
||||
remove
|
||||
};
|
||||
}
|
||||
|
||||
describe('compareUsers()', () => {
|
||||
it('compares users correctly', () => {
|
||||
expect(
|
||||
[
|
||||
{ renderName: 'user5' },
|
||||
{ renderName: '@user2' },
|
||||
{ renderName: 'user3' },
|
||||
{ renderName: 'user2' },
|
||||
{ renderName: '+user1' },
|
||||
{ renderName: '~bob' },
|
||||
{ renderName: '%apples' },
|
||||
{ renderName: '&cake' }
|
||||
].sort(compareUsers)
|
||||
).toEqual([
|
||||
{ renderName: '~bob' },
|
||||
{ renderName: '&cake' },
|
||||
{ renderName: '@user2' },
|
||||
{ renderName: '%apples' },
|
||||
{ renderName: '+user1' },
|
||||
{ renderName: 'user2' },
|
||||
{ renderName: 'user3' },
|
||||
{ renderName: 'user5' }
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSortedChannels', () => {
|
||||
it('sorts servers and channels', () => {
|
||||
expect(
|
||||
getSortedChannels({
|
||||
channels: {
|
||||
'bob.com': {},
|
||||
'127.0.0.1': {
|
||||
'#chan1': {
|
||||
users: [],
|
||||
topic: 'cake'
|
||||
},
|
||||
'#pie': {},
|
||||
'##apples': {}
|
||||
}
|
||||
}
|
||||
})
|
||||
).toEqual([
|
||||
{
|
||||
address: '127.0.0.1',
|
||||
channels: ['##apples', '#chan1', '#pie']
|
||||
},
|
||||
{
|
||||
address: 'bob.com',
|
||||
channels: []
|
||||
}
|
||||
]);
|
||||
});
|
||||
});
|
184
client/js/state/__tests__/reducer-messages.test.js
Normal file
184
client/js/state/__tests__/reducer-messages.test.js
Normal file
|
@ -0,0 +1,184 @@
|
|||
import reducer, { broadcast, getMessageTab } from '../messages';
|
||||
import * as actions from '../actions';
|
||||
import appReducer from '../app';
|
||||
|
||||
describe('message reducer', () => {
|
||||
it('adds the message on ADD_MESSAGE', () => {
|
||||
const state = reducer(undefined, {
|
||||
type: actions.ADD_MESSAGE,
|
||||
server: 'srv',
|
||||
tab: '#chan1',
|
||||
message: {
|
||||
from: 'foo',
|
||||
content: 'msg'
|
||||
}
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
srv: {
|
||||
'#chan1': [
|
||||
{
|
||||
from: 'foo',
|
||||
content: 'msg'
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('adds all the messages on ADD_MESSAGES', () => {
|
||||
const state = reducer(undefined, {
|
||||
type: actions.ADD_MESSAGES,
|
||||
server: 'srv',
|
||||
tab: '#chan1',
|
||||
messages: [
|
||||
{
|
||||
from: 'foo',
|
||||
content: 'msg'
|
||||
},
|
||||
{
|
||||
from: 'bar',
|
||||
content: 'msg'
|
||||
},
|
||||
{
|
||||
tab: '#chan2',
|
||||
from: 'foo',
|
||||
content: 'msg'
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
srv: {
|
||||
'#chan1': [
|
||||
{
|
||||
from: 'foo',
|
||||
content: 'msg'
|
||||
},
|
||||
{
|
||||
from: 'bar',
|
||||
content: 'msg'
|
||||
}
|
||||
],
|
||||
'#chan2': [
|
||||
{
|
||||
from: 'foo',
|
||||
content: 'msg'
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('handles prepending of messages on ADD_MESSAGES', () => {
|
||||
let state = {
|
||||
srv: {
|
||||
'#chan1': [{ id: 0 }]
|
||||
}
|
||||
};
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.ADD_MESSAGES,
|
||||
server: 'srv',
|
||||
tab: '#chan1',
|
||||
prepend: true,
|
||||
messages: [{ id: 1 }, { id: 2 }]
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
srv: {
|
||||
'#chan1': [{ id: 1 }, { id: 2 }, { id: 0 }]
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('adds messages to the correct tabs when broadcasting', () => {
|
||||
let state = {
|
||||
app: appReducer(undefined, { type: '' })
|
||||
};
|
||||
|
||||
const thunk = broadcast('test', 'srv', ['#chan1', '#chan3']);
|
||||
thunk(
|
||||
action => {
|
||||
state.messages = reducer(undefined, action);
|
||||
},
|
||||
() => state
|
||||
);
|
||||
|
||||
const messages = state.messages;
|
||||
|
||||
expect(messages.srv).not.toHaveProperty('srv');
|
||||
expect(messages.srv['#chan1']).toHaveLength(1);
|
||||
expect(messages.srv['#chan1'][0].content).toBe('test');
|
||||
expect(messages.srv['#chan3']).toHaveLength(1);
|
||||
expect(messages.srv['#chan3'][0].content).toBe('test');
|
||||
});
|
||||
|
||||
it('deletes all messages related to server when disconnecting', () => {
|
||||
let state = {
|
||||
srv: {
|
||||
'#chan1': [{ content: 'msg1' }, { content: 'msg2' }],
|
||||
'#chan2': [{ content: 'msg' }]
|
||||
},
|
||||
srv2: {
|
||||
'#chan1': [{ content: 'msg' }]
|
||||
}
|
||||
};
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.DISCONNECT,
|
||||
server: 'srv'
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
srv2: {
|
||||
'#chan1': [{ content: 'msg' }]
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes all messages related to channel when parting', () => {
|
||||
let state = {
|
||||
srv: {
|
||||
'#chan1': [{ content: 'msg1' }, { content: 'msg2' }],
|
||||
'#chan2': [{ content: 'msg' }]
|
||||
},
|
||||
srv2: {
|
||||
'#chan1': [{ content: 'msg' }]
|
||||
}
|
||||
};
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.PART,
|
||||
server: 'srv',
|
||||
channels: ['#chan1']
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {
|
||||
'#chan2': [{ content: 'msg' }]
|
||||
},
|
||||
srv2: {
|
||||
'#chan1': [{ content: 'msg' }]
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getMessageTab()', () => {
|
||||
it('returns the correct tab', () => {
|
||||
const srv = 'chat.freenode.net';
|
||||
[
|
||||
['#cake', '#cake'],
|
||||
['#apple.pie', '#apple.pie'],
|
||||
['bob', 'bob'],
|
||||
[undefined, srv],
|
||||
[null, srv],
|
||||
['*', srv],
|
||||
[srv, srv],
|
||||
['beans.freenode.net', srv]
|
||||
].forEach(([target, expected]) =>
|
||||
expect(getMessageTab(srv, target)).toBe(expected)
|
||||
);
|
||||
});
|
||||
});
|
273
client/js/state/__tests__/reducer-servers.test.js
Normal file
273
client/js/state/__tests__/reducer-servers.test.js
Normal file
|
@ -0,0 +1,273 @@
|
|||
import reducer, { connect, setServerName } from '../servers';
|
||||
import * as actions from '../actions';
|
||||
|
||||
describe('server reducer', () => {
|
||||
it('adds the server on CONNECT', () => {
|
||||
let state = reducer(
|
||||
undefined,
|
||||
connect({ host: '127.0.0.1', nick: 'nick' })
|
||||
);
|
||||
|
||||
expect(state).toEqual({
|
||||
'127.0.0.1': {
|
||||
name: '127.0.0.1',
|
||||
nick: 'nick',
|
||||
editedNick: null,
|
||||
status: {
|
||||
connected: false,
|
||||
error: null
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
state = reducer(state, connect({ host: '127.0.0.1', nick: 'nick' }));
|
||||
|
||||
expect(state).toEqual({
|
||||
'127.0.0.1': {
|
||||
name: '127.0.0.1',
|
||||
nick: 'nick',
|
||||
editedNick: null,
|
||||
status: {
|
||||
connected: false,
|
||||
error: null
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
state = reducer(
|
||||
state,
|
||||
connect({ host: '127.0.0.2', nick: 'nick', name: 'srv' })
|
||||
);
|
||||
|
||||
expect(state).toEqual({
|
||||
'127.0.0.1': {
|
||||
name: '127.0.0.1',
|
||||
nick: 'nick',
|
||||
editedNick: null,
|
||||
status: {
|
||||
connected: false,
|
||||
error: null
|
||||
}
|
||||
},
|
||||
'127.0.0.2': {
|
||||
name: 'srv',
|
||||
nick: 'nick',
|
||||
editedNick: null,
|
||||
status: {
|
||||
connected: false,
|
||||
error: null
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('removes the server on DISCONNECT', () => {
|
||||
let state = {
|
||||
srv: {},
|
||||
srv2: {}
|
||||
};
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.DISCONNECT,
|
||||
server: 'srv2'
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {}
|
||||
});
|
||||
});
|
||||
|
||||
it('handles SET_SERVER_NAME', () => {
|
||||
let state = {
|
||||
srv: {
|
||||
name: 'cake'
|
||||
}
|
||||
};
|
||||
|
||||
state = reducer(state, setServerName('pie', 'srv'));
|
||||
|
||||
expect(state).toEqual({
|
||||
srv: {
|
||||
name: 'pie'
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('sets editedNick when editing the nick', () => {
|
||||
let state = reducer(
|
||||
undefined,
|
||||
connect({ host: '127.0.0.1', nick: 'nick' })
|
||||
);
|
||||
state = reducer(state, {
|
||||
type: actions.SET_NICK,
|
||||
server: '127.0.0.1',
|
||||
nick: 'nick2',
|
||||
editing: true
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
'127.0.0.1': {
|
||||
name: '127.0.0.1',
|
||||
nick: 'nick',
|
||||
editedNick: 'nick2'
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('clears editedNick when receiving an empty nick after editing finishes', () => {
|
||||
let state = reducer(
|
||||
undefined,
|
||||
connect({ host: '127.0.0.1', nick: 'nick' })
|
||||
);
|
||||
state = reducer(state, {
|
||||
type: actions.SET_NICK,
|
||||
server: '127.0.0.1',
|
||||
nick: 'nick2',
|
||||
editing: true
|
||||
});
|
||||
state = reducer(state, {
|
||||
type: actions.SET_NICK,
|
||||
server: '127.0.0.1',
|
||||
nick: ''
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
'127.0.0.1': {
|
||||
name: '127.0.0.1',
|
||||
nick: 'nick',
|
||||
editedNick: null
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('updates the nick on SOCKET_NICK', () => {
|
||||
let state = reducer(
|
||||
undefined,
|
||||
connect({ host: '127.0.0.1', nick: 'nick' })
|
||||
);
|
||||
state = reducer(state, {
|
||||
type: actions.socket.NICK,
|
||||
server: '127.0.0.1',
|
||||
oldNick: 'nick',
|
||||
newNick: 'nick2'
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
'127.0.0.1': {
|
||||
name: '127.0.0.1',
|
||||
nick: 'nick2',
|
||||
editedNick: null
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('clears editedNick on SOCKET_NICK_FAIL', () => {
|
||||
let state = reducer(
|
||||
undefined,
|
||||
connect({ host: '127.0.0.1', nick: 'nick' })
|
||||
);
|
||||
state = reducer(state, {
|
||||
type: actions.SET_NICK,
|
||||
server: '127.0.0.1',
|
||||
nick: 'nick2',
|
||||
editing: true
|
||||
});
|
||||
state = reducer(state, {
|
||||
type: actions.socket.NICK_FAIL,
|
||||
server: '127.0.0.1'
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
'127.0.0.1': {
|
||||
name: '127.0.0.1',
|
||||
nick: 'nick',
|
||||
editedNick: null
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('adds the servers on SOCKET_SERVERS', () => {
|
||||
let state = reducer(undefined, {
|
||||
type: actions.socket.SERVERS,
|
||||
data: [
|
||||
{
|
||||
host: '127.0.0.1',
|
||||
name: 'stuff',
|
||||
nick: 'nick',
|
||||
status: {
|
||||
connected: true
|
||||
}
|
||||
},
|
||||
{
|
||||
host: '127.0.0.2',
|
||||
name: 'stuffz',
|
||||
nick: 'nick2',
|
||||
status: {
|
||||
connected: false
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
'127.0.0.1': {
|
||||
name: 'stuff',
|
||||
nick: 'nick',
|
||||
editedNick: null,
|
||||
status: {
|
||||
connected: true
|
||||
}
|
||||
},
|
||||
'127.0.0.2': {
|
||||
name: 'stuffz',
|
||||
nick: 'nick2',
|
||||
editedNick: null,
|
||||
status: {
|
||||
connected: false
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('updates connection status on SOCKET_CONNECTION_UPDATE', () => {
|
||||
let state = reducer(
|
||||
undefined,
|
||||
connect({ host: '127.0.0.1', nick: 'nick' })
|
||||
);
|
||||
state = reducer(state, {
|
||||
type: actions.socket.CONNECTION_UPDATE,
|
||||
server: '127.0.0.1',
|
||||
connected: true
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
'127.0.0.1': {
|
||||
name: '127.0.0.1',
|
||||
nick: 'nick',
|
||||
editedNick: null,
|
||||
status: {
|
||||
connected: true
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.socket.CONNECTION_UPDATE,
|
||||
server: '127.0.0.1',
|
||||
connected: false,
|
||||
error: 'Bad stuff happened'
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
'127.0.0.1': {
|
||||
name: '127.0.0.1',
|
||||
nick: 'nick',
|
||||
editedNick: null,
|
||||
status: {
|
||||
connected: false,
|
||||
error: 'Bad stuff happened'
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
110
client/js/state/__tests__/reducer-tab.test.js
Normal file
110
client/js/state/__tests__/reducer-tab.test.js
Normal file
|
@ -0,0 +1,110 @@
|
|||
import reducer, { setSelectedTab } from '../tab';
|
||||
import * as actions from '../actions';
|
||||
import { locationChanged } from 'utils/router';
|
||||
|
||||
describe('tab reducer', () => {
|
||||
it('selects the tab and adds it to history', () => {
|
||||
let state = reducer(undefined, setSelectedTab('srv', '#chan'));
|
||||
|
||||
expect(state).toEqual({
|
||||
selected: { server: 'srv', name: '#chan' },
|
||||
history: [{ server: 'srv', name: '#chan' }]
|
||||
});
|
||||
|
||||
state = reducer(state, setSelectedTab('srv', 'user1'));
|
||||
|
||||
expect(state).toEqual({
|
||||
selected: { server: 'srv', name: 'user1' },
|
||||
history: [
|
||||
{ server: 'srv', name: '#chan' },
|
||||
{ server: 'srv', name: 'user1' }
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it('removes the tab from history on PART', () => {
|
||||
let state = reducer(undefined, setSelectedTab('srv', '#chan'));
|
||||
state = reducer(state, setSelectedTab('srv1', 'bob'));
|
||||
state = reducer(state, setSelectedTab('srv', '#chan'));
|
||||
state = reducer(state, setSelectedTab('srv', '#chan3'));
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.PART,
|
||||
server: 'srv',
|
||||
channels: ['#chan']
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
selected: { server: 'srv', name: '#chan3' },
|
||||
history: [
|
||||
{ server: 'srv1', name: 'bob' },
|
||||
{ server: 'srv', name: '#chan3' }
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it('removes the tab from history on CLOSE_PRIVATE_CHAT', () => {
|
||||
let state = reducer(undefined, setSelectedTab('srv', '#chan'));
|
||||
state = reducer(state, setSelectedTab('srv1', 'bob'));
|
||||
state = reducer(state, setSelectedTab('srv', '#chan'));
|
||||
state = reducer(state, setSelectedTab('srv', '#chan3'));
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.CLOSE_PRIVATE_CHAT,
|
||||
server: 'srv1',
|
||||
nick: 'bob'
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
selected: { server: 'srv', name: '#chan3' },
|
||||
history: [
|
||||
{ server: 'srv', name: '#chan' },
|
||||
{ server: 'srv', name: '#chan' },
|
||||
{ server: 'srv', name: '#chan3' }
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it('removes all tabs related to server from history on DISCONNECT', () => {
|
||||
let state = reducer(undefined, setSelectedTab('srv', '#chan'));
|
||||
state = reducer(state, setSelectedTab('srv1', 'bob'));
|
||||
state = reducer(state, setSelectedTab('srv', '#chan'));
|
||||
state = reducer(state, setSelectedTab('srv', '#chan3'));
|
||||
|
||||
state = reducer(state, {
|
||||
type: actions.DISCONNECT,
|
||||
server: 'srv'
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
selected: { server: 'srv', name: '#chan3' },
|
||||
history: [{ server: 'srv1', name: 'bob' }]
|
||||
});
|
||||
});
|
||||
|
||||
it('clears the tab when navigating to a non-tab page', () => {
|
||||
let state = reducer(undefined, setSelectedTab('srv', '#chan'));
|
||||
|
||||
state = reducer(state, locationChanged('settings'));
|
||||
|
||||
expect(state).toEqual({
|
||||
selected: {},
|
||||
history: [{ server: 'srv', name: '#chan' }]
|
||||
});
|
||||
});
|
||||
|
||||
it('selects the tab and adds it to history when navigating to a tab', () => {
|
||||
const state = reducer(
|
||||
undefined,
|
||||
locationChanged('chat', {
|
||||
server: 'srv',
|
||||
name: '#chan'
|
||||
})
|
||||
);
|
||||
|
||||
expect(state).toEqual({
|
||||
selected: { server: 'srv', name: '#chan' },
|
||||
history: [{ server: 'srv', name: '#chan' }]
|
||||
});
|
||||
});
|
||||
});
|
77
client/js/state/actions.js
Normal file
77
client/js/state/actions.js
Normal file
|
@ -0,0 +1,77 @@
|
|||
export const APP_SET = 'APP_SET';
|
||||
|
||||
export const INVITE = 'INVITE';
|
||||
export const JOIN = 'JOIN';
|
||||
export const KICK = 'KICK';
|
||||
export const PART = 'PART';
|
||||
export const SET_TOPIC = 'SET_TOPIC';
|
||||
|
||||
export const INPUT_HISTORY_ADD = 'INPUT_HISTORY_ADD';
|
||||
export const INPUT_HISTORY_DECREMENT = 'INPUT_HISTORY_DECREMENT';
|
||||
export const INPUT_HISTORY_INCREMENT = 'INPUT_HISTORY_INCREMENT';
|
||||
export const INPUT_HISTORY_RESET = 'INPUT_HISTORY_RESET';
|
||||
|
||||
export const ADD_FETCHED_MESSAGES = 'ADD_FETCHED_MESSAGES';
|
||||
export const ADD_MESSAGE = 'ADD_MESSAGE';
|
||||
export const ADD_MESSAGES = 'ADD_MESSAGES';
|
||||
export const COMMAND = 'COMMAND';
|
||||
export const FETCH_MESSAGES = 'FETCH_MESSAGES';
|
||||
export const RAW = 'RAW';
|
||||
export const UPDATE_MESSAGE_HEIGHT = 'UPDATE_MESSAGE_HEIGHT';
|
||||
|
||||
export const CLOSE_PRIVATE_CHAT = 'CLOSE_PRIVATE_CHAT';
|
||||
export const OPEN_PRIVATE_CHAT = 'OPEN_PRIVATE_CHAT';
|
||||
|
||||
export const SEARCH_MESSAGES = 'SEARCH_MESSAGES';
|
||||
export const TOGGLE_SEARCH = 'TOGGLE_SEARCH';
|
||||
|
||||
export const AWAY = 'AWAY';
|
||||
export const CONNECT = 'CONNECT';
|
||||
export const DISCONNECT = 'DISCONNECT';
|
||||
export const RECONNECT = 'RECONNECT';
|
||||
export const SET_NICK = 'SET_NICK';
|
||||
export const SET_SERVER_NAME = 'SET_SERVER_NAME';
|
||||
export const WHOIS = 'WHOIS';
|
||||
|
||||
export const SET_CERT = 'SET_CERT';
|
||||
export const SET_CERT_ERROR = 'SET_CERT_ERROR';
|
||||
export const SET_KEY = 'SET_KEY';
|
||||
export const UPLOAD_CERT = 'UPLOAD_CERT';
|
||||
export const SETTINGS_SET = 'SETTINGS_SET';
|
||||
|
||||
export const SELECT_TAB = 'SELECT_TAB';
|
||||
|
||||
export const HIDE_MENU = 'HIDE_MENU';
|
||||
export const TOGGLE_MENU = 'TOGGLE_MENU';
|
||||
export const TOGGLE_USERLIST = 'TOGGLE_USERLIST';
|
||||
|
||||
export function socketAction(type) {
|
||||
return `SOCKET_${type.toUpperCase()}`;
|
||||
}
|
||||
|
||||
function createSocketActions(types) {
|
||||
const actions = {};
|
||||
types.forEach(type => {
|
||||
actions[type.toUpperCase()] = socketAction(type);
|
||||
});
|
||||
return actions;
|
||||
}
|
||||
|
||||
export const socket = createSocketActions([
|
||||
'cert_fail',
|
||||
'cert_success',
|
||||
'channels',
|
||||
'connection_update',
|
||||
'join',
|
||||
'message',
|
||||
'mode',
|
||||
'nick_fail',
|
||||
'nick',
|
||||
'part',
|
||||
'pm',
|
||||
'quit',
|
||||
'search',
|
||||
'servers',
|
||||
'topic',
|
||||
'users'
|
||||
]);
|
60
client/js/state/app.js
Normal file
60
client/js/state/app.js
Normal file
|
@ -0,0 +1,60 @@
|
|||
import createReducer from 'utils/createReducer';
|
||||
import * as actions from './actions';
|
||||
|
||||
export const getApp = state => state.app;
|
||||
export const getConnected = state => state.app.connected;
|
||||
export const getWrapWidth = state => state.app.wrapWidth;
|
||||
export const getCharWidth = state => state.app.charWidth;
|
||||
export const getWindowWidth = state => state.app.windowWidth;
|
||||
export const getConnectDefaults = state => state.app.connectDefaults;
|
||||
|
||||
const initialState = {
|
||||
connected: true,
|
||||
wrapWidth: 0,
|
||||
charWidth: 0,
|
||||
windowWidth: 0,
|
||||
connectDefaults: {
|
||||
name: '',
|
||||
address: '',
|
||||
channels: [],
|
||||
ssl: false,
|
||||
password: false,
|
||||
readonly: false,
|
||||
showDetails: false
|
||||
},
|
||||
hexIP: false,
|
||||
newVersionAvailable: false,
|
||||
installable: null
|
||||
};
|
||||
|
||||
export default createReducer(initialState, {
|
||||
[actions.APP_SET](state, { key, value }) {
|
||||
state[key] = value;
|
||||
},
|
||||
|
||||
[actions.UPDATE_MESSAGE_HEIGHT](state, action) {
|
||||
state.wrapWidth = action.wrapWidth;
|
||||
state.charWidth = action.charWidth;
|
||||
state.windowWidth = action.windowWidth;
|
||||
}
|
||||
});
|
||||
|
||||
export function appSet(key, value) {
|
||||
return {
|
||||
type: actions.APP_SET,
|
||||
key,
|
||||
value
|
||||
};
|
||||
}
|
||||
|
||||
export function setConnected(connected) {
|
||||
return appSet('connected', connected);
|
||||
}
|
||||
|
||||
export function setCharWidth(width) {
|
||||
return appSet('charWidth', width);
|
||||
}
|
||||
|
||||
export function setConnectDefaults(defaults) {
|
||||
return appSet('connectDefaults', defaults);
|
||||
}
|
277
client/js/state/channels.js
Normal file
277
client/js/state/channels.js
Normal file
|
@ -0,0 +1,277 @@
|
|||
import { createSelector } from 'reselect';
|
||||
import get from 'lodash/get';
|
||||
import sortBy from 'lodash/sortBy';
|
||||
import createReducer from 'utils/createReducer';
|
||||
import { find, findIndex } from 'utils';
|
||||
import { getSelectedTab, updateSelection } from './tab';
|
||||
import * as actions from './actions';
|
||||
|
||||
const modePrefixes = [
|
||||
{ mode: 'q', prefix: '~' }, // Owner
|
||||
{ mode: 'a', prefix: '&' }, // Admin
|
||||
{ mode: 'o', prefix: '@' }, // Op
|
||||
{ mode: 'h', prefix: '%' }, // Halfop
|
||||
{ mode: 'v', prefix: '+' } // Voice
|
||||
];
|
||||
|
||||
function getRenderName(user) {
|
||||
for (let i = 0; i < modePrefixes.length; i++) {
|
||||
if (user.mode.indexOf(modePrefixes[i].mode) !== -1) {
|
||||
return `${modePrefixes[i].prefix}${user.nick}`;
|
||||
}
|
||||
}
|
||||
|
||||
return user.nick;
|
||||
}
|
||||
|
||||
function createUser(nick, mode) {
|
||||
const user = {
|
||||
nick,
|
||||
mode: mode || ''
|
||||
};
|
||||
user.renderName = getRenderName(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
function loadUser(nick) {
|
||||
let mode;
|
||||
|
||||
for (let i = 0; i < modePrefixes.length; i++) {
|
||||
if (nick[0] === modePrefixes[i].prefix) {
|
||||
({ mode } = modePrefixes[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (mode) {
|
||||
return createUser(nick.slice(1), mode);
|
||||
}
|
||||
|
||||
return createUser(nick);
|
||||
}
|
||||
|
||||
function removeUser(users, nick) {
|
||||
const i = findIndex(users, u => u.nick === nick);
|
||||
if (i !== -1) {
|
||||
users.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
function init(state, server, channel) {
|
||||
if (!state[server]) {
|
||||
state[server] = {};
|
||||
}
|
||||
if (channel && !state[server][channel]) {
|
||||
state[server][channel] = { users: [] };
|
||||
}
|
||||
}
|
||||
|
||||
export function compareUsers(a, b) {
|
||||
a = a.renderName.toLowerCase();
|
||||
b = b.renderName.toLowerCase();
|
||||
|
||||
for (let i = 0; i < modePrefixes.length; i++) {
|
||||
const { prefix } = modePrefixes[i];
|
||||
|
||||
if (a[0] === prefix && b[0] !== prefix) {
|
||||
return -1;
|
||||
}
|
||||
if (b[0] === prefix && a[0] !== prefix) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (a < b) {
|
||||
return -1;
|
||||
}
|
||||
if (a > b) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export const getChannels = state => state.channels;
|
||||
|
||||
export const getSortedChannels = createSelector(getChannels, channels =>
|
||||
sortBy(
|
||||
Object.keys(channels).map(server => ({
|
||||
address: server,
|
||||
channels: sortBy(Object.keys(channels[server]), channel =>
|
||||
channel.toLowerCase()
|
||||
)
|
||||
})),
|
||||
server => server.address.toLowerCase()
|
||||
)
|
||||
);
|
||||
|
||||
export const getSelectedChannel = createSelector(
|
||||
getSelectedTab,
|
||||
getChannels,
|
||||
(tab, channels) => get(channels, [tab.server, tab.name])
|
||||
);
|
||||
|
||||
export const getSelectedChannelUsers = createSelector(
|
||||
getSelectedChannel,
|
||||
channel => {
|
||||
if (channel) {
|
||||
return channel.users.concat().sort(compareUsers);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
);
|
||||
|
||||
export default createReducer(
|
||||
{},
|
||||
{
|
||||
[actions.PART](state, { server, channels }) {
|
||||
channels.forEach(channel => delete state[server][channel]);
|
||||
},
|
||||
|
||||
[actions.socket.JOIN](state, { server, channels, user }) {
|
||||
const channel = channels[0];
|
||||
init(state, server, channel);
|
||||
state[server][channel].users.push(createUser(user));
|
||||
},
|
||||
|
||||
[actions.socket.PART](state, { server, channel, user }) {
|
||||
if (state[server][channel]) {
|
||||
removeUser(state[server][channel].users, user);
|
||||
}
|
||||
},
|
||||
|
||||
[actions.socket.QUIT](state, { server, user }) {
|
||||
Object.keys(state[server]).forEach(channel => {
|
||||
removeUser(state[server][channel].users, user);
|
||||
});
|
||||
},
|
||||
|
||||
[actions.socket.NICK](state, { server, oldNick, newNick }) {
|
||||
Object.keys(state[server]).forEach(channel => {
|
||||
const user = find(
|
||||
state[server][channel].users,
|
||||
u => u.nick === oldNick
|
||||
);
|
||||
if (user) {
|
||||
user.nick = newNick;
|
||||
user.renderName = getRenderName(user);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
[actions.socket.USERS](state, { server, channel, users }) {
|
||||
init(state, server, channel);
|
||||
state[server][channel].users = users.map(nick => loadUser(nick));
|
||||
},
|
||||
|
||||
[actions.socket.TOPIC](state, { server, channel, topic }) {
|
||||
init(state, server, channel);
|
||||
state[server][channel].topic = topic;
|
||||
},
|
||||
|
||||
[actions.socket.MODE](state, { server, channel, user, remove, add }) {
|
||||
const u = find(state[server][channel].users, v => v.nick === user);
|
||||
if (u) {
|
||||
if (remove) {
|
||||
let j = remove.length;
|
||||
while (j--) {
|
||||
u.mode = u.mode.replace(remove[j], '');
|
||||
}
|
||||
}
|
||||
|
||||
if (add) {
|
||||
u.mode += add;
|
||||
}
|
||||
|
||||
u.renderName = getRenderName(u);
|
||||
}
|
||||
},
|
||||
|
||||
[actions.socket.CHANNELS](state, { data }) {
|
||||
if (data) {
|
||||
data.forEach(({ server, name, topic }) => {
|
||||
init(state, server, name);
|
||||
state[server][name].topic = topic;
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
[actions.socket.SERVERS](state, { data }) {
|
||||
if (data) {
|
||||
data.forEach(({ host }) => init(state, host));
|
||||
}
|
||||
},
|
||||
|
||||
[actions.CONNECT](state, { host }) {
|
||||
init(state, host);
|
||||
},
|
||||
|
||||
[actions.DISCONNECT](state, { server }) {
|
||||
delete state[server];
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export function join(channels, server) {
|
||||
return {
|
||||
type: actions.JOIN,
|
||||
channels,
|
||||
server,
|
||||
socket: {
|
||||
type: 'join',
|
||||
data: { channels, server }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function part(channels, server) {
|
||||
return dispatch => {
|
||||
dispatch({
|
||||
type: actions.PART,
|
||||
channels,
|
||||
server,
|
||||
socket: {
|
||||
type: 'part',
|
||||
data: { channels, server }
|
||||
}
|
||||
});
|
||||
dispatch(updateSelection());
|
||||
};
|
||||
}
|
||||
|
||||
export function invite(user, channel, server) {
|
||||
return {
|
||||
type: actions.INVITE,
|
||||
user,
|
||||
channel,
|
||||
server,
|
||||
socket: {
|
||||
type: 'invite',
|
||||
data: { user, channel, server }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function kick(user, channel, server) {
|
||||
return {
|
||||
type: actions.KICK,
|
||||
user,
|
||||
channel,
|
||||
server,
|
||||
socket: {
|
||||
type: 'kick',
|
||||
data: { user, channel, server }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function setTopic(topic, channel, server) {
|
||||
return {
|
||||
type: actions.SET_TOPIC,
|
||||
topic,
|
||||
channel,
|
||||
server,
|
||||
socket: {
|
||||
type: 'topic',
|
||||
data: { topic, channel, server }
|
||||
}
|
||||
};
|
||||
}
|
30
client/js/state/index.js
Normal file
30
client/js/state/index.js
Normal file
|
@ -0,0 +1,30 @@
|
|||
import { combineReducers } from 'redux';
|
||||
import app from './app';
|
||||
import channels from './channels';
|
||||
import input from './input';
|
||||
import messages from './messages';
|
||||
import privateChats from './privateChats';
|
||||
import search from './search';
|
||||
import servers from './servers';
|
||||
import settings from './settings';
|
||||
import tab from './tab';
|
||||
import ui from './ui';
|
||||
|
||||
export * from './selectors';
|
||||
export const getRouter = state => state.router;
|
||||
|
||||
export default function createReducer(router) {
|
||||
return combineReducers({
|
||||
router,
|
||||
app,
|
||||
channels,
|
||||
input,
|
||||
messages,
|
||||
privateChats,
|
||||
search,
|
||||
servers,
|
||||
settings,
|
||||
tab,
|
||||
ui
|
||||
});
|
||||
}
|
69
client/js/state/input.js
Normal file
69
client/js/state/input.js
Normal file
|
@ -0,0 +1,69 @@
|
|||
import createReducer from 'utils/createReducer';
|
||||
import * as actions from './actions';
|
||||
|
||||
const HISTORY_MAX_LENGTH = 128;
|
||||
|
||||
const initialState = {
|
||||
history: [],
|
||||
index: 0
|
||||
};
|
||||
|
||||
export const getCurrentInputHistoryEntry = state => {
|
||||
if (state.input.index === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return state.input.history[state.input.index];
|
||||
};
|
||||
|
||||
export default createReducer(initialState, {
|
||||
[actions.INPUT_HISTORY_ADD](state, { line }) {
|
||||
if (line.trim() && line !== state.history[0]) {
|
||||
if (state.history.length === HISTORY_MAX_LENGTH) {
|
||||
state.history.pop();
|
||||
}
|
||||
state.history.unshift(line);
|
||||
}
|
||||
},
|
||||
|
||||
[actions.INPUT_HISTORY_RESET](state) {
|
||||
state.index = -1;
|
||||
},
|
||||
|
||||
[actions.INPUT_HISTORY_INCREMENT](state) {
|
||||
if (state.index < state.history.length - 1) {
|
||||
state.index++;
|
||||
}
|
||||
},
|
||||
|
||||
[actions.INPUT_HISTORY_DECREMENT](state) {
|
||||
if (state.index >= 0) {
|
||||
state.index--;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export function addInputHistory(line) {
|
||||
return {
|
||||
type: actions.INPUT_HISTORY_ADD,
|
||||
line
|
||||
};
|
||||
}
|
||||
|
||||
export function resetInputHistory() {
|
||||
return {
|
||||
type: actions.INPUT_HISTORY_RESET
|
||||
};
|
||||
}
|
||||
|
||||
export function incrementInputHistory() {
|
||||
return {
|
||||
type: actions.INPUT_HISTORY_INCREMENT
|
||||
};
|
||||
}
|
||||
|
||||
export function decrementInputHistory() {
|
||||
return {
|
||||
type: actions.INPUT_HISTORY_DECREMENT
|
||||
};
|
||||
}
|
314
client/js/state/messages.js
Normal file
314
client/js/state/messages.js
Normal file
|
@ -0,0 +1,314 @@
|
|||
import { createSelector } from 'reselect';
|
||||
import has from 'lodash/has';
|
||||
import {
|
||||
findBreakpoints,
|
||||
messageHeight,
|
||||
linkify,
|
||||
timestamp,
|
||||
isChannel
|
||||
} from 'utils';
|
||||
import createReducer from 'utils/createReducer';
|
||||
import { getApp } from './app';
|
||||
import { getSelectedTab } from './tab';
|
||||
import * as actions from './actions';
|
||||
|
||||
export const getMessages = state => state.messages;
|
||||
|
||||
export const getSelectedMessages = createSelector(
|
||||
getSelectedTab,
|
||||
getMessages,
|
||||
(tab, messages) => {
|
||||
const target = tab.name || tab.server;
|
||||
if (has(messages, [tab.server, target])) {
|
||||
return messages[tab.server][target];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
);
|
||||
|
||||
export const getHasMoreMessages = createSelector(
|
||||
getSelectedMessages,
|
||||
messages => {
|
||||
const first = messages[0];
|
||||
return first && first.next;
|
||||
}
|
||||
);
|
||||
|
||||
function init(state, server, tab) {
|
||||
if (!state[server]) {
|
||||
state[server] = {};
|
||||
}
|
||||
if (!state[server][tab]) {
|
||||
state[server][tab] = [];
|
||||
}
|
||||
}
|
||||
|
||||
export default createReducer(
|
||||
{},
|
||||
{
|
||||
[actions.ADD_MESSAGE](state, { server, tab, message }) {
|
||||
init(state, server, tab);
|
||||
state[server][tab].push(message);
|
||||
},
|
||||
|
||||
[actions.ADD_MESSAGES](state, { server, tab, messages, prepend }) {
|
||||
if (prepend) {
|
||||
init(state, server, tab);
|
||||
state[server][tab].unshift(...messages);
|
||||
} else {
|
||||
messages.forEach(message => {
|
||||
init(state, server, message.tab || tab);
|
||||
state[server][message.tab || tab].push(message);
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
[actions.DISCONNECT](state, { server }) {
|
||||
delete state[server];
|
||||
},
|
||||
|
||||
[actions.PART](state, { server, channels }) {
|
||||
channels.forEach(channel => delete state[server][channel]);
|
||||
},
|
||||
|
||||
[actions.UPDATE_MESSAGE_HEIGHT](
|
||||
state,
|
||||
{ wrapWidth, charWidth, windowWidth }
|
||||
) {
|
||||
Object.keys(state).forEach(server =>
|
||||
Object.keys(state[server]).forEach(target =>
|
||||
state[server][target].forEach(message => {
|
||||
message.height = messageHeight(
|
||||
message,
|
||||
wrapWidth,
|
||||
charWidth,
|
||||
6 * charWidth,
|
||||
windowWidth
|
||||
);
|
||||
})
|
||||
)
|
||||
);
|
||||
},
|
||||
|
||||
[actions.socket.SERVERS](state, { data }) {
|
||||
if (data) {
|
||||
data.forEach(({ host }) => {
|
||||
state[host] = {};
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
let nextID = 0;
|
||||
|
||||
function initMessage(message, tab, state) {
|
||||
if (message.time) {
|
||||
message.time = timestamp(new Date(message.time * 1000));
|
||||
} else {
|
||||
message.time = timestamp();
|
||||
}
|
||||
|
||||
if (!message.id) {
|
||||
message.id = nextID;
|
||||
nextID++;
|
||||
}
|
||||
|
||||
if (tab.charAt(0) === '#') {
|
||||
message.channel = true;
|
||||
}
|
||||
|
||||
// Collapse multiple adjacent spaces into a single one
|
||||
message.content = message.content.replace(/\s\s+/g, ' ');
|
||||
|
||||
if (message.content.indexOf('\x01ACTION') === 0) {
|
||||
const { from } = message;
|
||||
message.from = null;
|
||||
message.type = 'action';
|
||||
message.content = from + message.content.slice(7, -1);
|
||||
}
|
||||
|
||||
const { wrapWidth, charWidth, windowWidth } = getApp(state);
|
||||
|
||||
message.length = message.content.length;
|
||||
message.breakpoints = findBreakpoints(message.content);
|
||||
message.height = messageHeight(
|
||||
message,
|
||||
wrapWidth,
|
||||
charWidth,
|
||||
6 * charWidth,
|
||||
windowWidth
|
||||
);
|
||||
message.content = linkify(message.content);
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
export function getMessageTab(server, to) {
|
||||
if (!to || to === '*' || (!isChannel(to) && to.indexOf('.') !== -1)) {
|
||||
return server;
|
||||
}
|
||||
return to;
|
||||
}
|
||||
|
||||
export function fetchMessages() {
|
||||
return (dispatch, getState) => {
|
||||
const state = getState();
|
||||
const first = getSelectedMessages(state)[0];
|
||||
|
||||
if (!first) {
|
||||
return;
|
||||
}
|
||||
|
||||
const tab = state.tab.selected;
|
||||
if (isChannel(tab)) {
|
||||
dispatch({
|
||||
type: actions.FETCH_MESSAGES,
|
||||
socket: {
|
||||
type: 'fetch_messages',
|
||||
data: {
|
||||
server: tab.server,
|
||||
channel: tab.name,
|
||||
next: first.id
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function addFetchedMessages(server, tab) {
|
||||
return {
|
||||
type: actions.ADD_FETCHED_MESSAGES,
|
||||
server,
|
||||
tab
|
||||
};
|
||||
}
|
||||
|
||||
export function updateMessageHeight(wrapWidth, charWidth, windowWidth) {
|
||||
return {
|
||||
type: actions.UPDATE_MESSAGE_HEIGHT,
|
||||
wrapWidth,
|
||||
charWidth,
|
||||
windowWidth
|
||||
};
|
||||
}
|
||||
|
||||
export function sendMessage(content, to, server) {
|
||||
return (dispatch, getState) => {
|
||||
const state = getState();
|
||||
|
||||
dispatch({
|
||||
type: actions.ADD_MESSAGE,
|
||||
server,
|
||||
tab: to,
|
||||
message: initMessage(
|
||||
{
|
||||
from: state.servers[server].nick,
|
||||
content
|
||||
},
|
||||
to,
|
||||
state
|
||||
),
|
||||
socket: {
|
||||
type: 'message',
|
||||
data: { content, to, server }
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export function addMessage(message, server, to) {
|
||||
const tab = getMessageTab(server, to);
|
||||
|
||||
return (dispatch, getState) =>
|
||||
dispatch({
|
||||
type: actions.ADD_MESSAGE,
|
||||
server,
|
||||
tab,
|
||||
message: initMessage(message, tab, getState())
|
||||
});
|
||||
}
|
||||
|
||||
export function addMessages(messages, server, to, prepend, next) {
|
||||
const tab = getMessageTab(server, to);
|
||||
|
||||
return (dispatch, getState) => {
|
||||
const state = getState();
|
||||
|
||||
if (next) {
|
||||
messages[0].id = next;
|
||||
messages[0].next = true;
|
||||
}
|
||||
|
||||
messages.forEach(message =>
|
||||
initMessage(message, message.tab || tab, state)
|
||||
);
|
||||
|
||||
dispatch({
|
||||
type: actions.ADD_MESSAGES,
|
||||
server,
|
||||
tab,
|
||||
messages,
|
||||
prepend
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export function broadcast(message, server, channels) {
|
||||
return addMessages(
|
||||
channels.map(channel => ({
|
||||
tab: channel,
|
||||
content: message,
|
||||
type: 'info'
|
||||
})),
|
||||
server
|
||||
);
|
||||
}
|
||||
|
||||
export function print(message, server, channel, type) {
|
||||
if (Array.isArray(message)) {
|
||||
return addMessages(
|
||||
message.map(line => ({
|
||||
content: line,
|
||||
type
|
||||
})),
|
||||
server,
|
||||
channel
|
||||
);
|
||||
}
|
||||
|
||||
return addMessage(
|
||||
{
|
||||
content: message,
|
||||
type
|
||||
},
|
||||
server,
|
||||
channel
|
||||
);
|
||||
}
|
||||
|
||||
export function inform(message, server, channel) {
|
||||
return print(message, server, channel, 'info');
|
||||
}
|
||||
|
||||
export function runCommand(command, channel, server) {
|
||||
return {
|
||||
type: actions.COMMAND,
|
||||
command,
|
||||
channel,
|
||||
server
|
||||
};
|
||||
}
|
||||
|
||||
export function raw(message, server) {
|
||||
return {
|
||||
type: actions.RAW,
|
||||
message,
|
||||
server,
|
||||
socket: {
|
||||
type: 'raw',
|
||||
data: { message, server }
|
||||
}
|
||||
};
|
||||
}
|
62
client/js/state/privateChats.js
Normal file
62
client/js/state/privateChats.js
Normal file
|
@ -0,0 +1,62 @@
|
|||
import sortBy from 'lodash/sortBy';
|
||||
import { findIndex } from 'utils';
|
||||
import createReducer from 'utils/createReducer';
|
||||
import { updateSelection } from './tab';
|
||||
import * as actions from './actions';
|
||||
|
||||
export const getPrivateChats = state => state.privateChats;
|
||||
|
||||
function open(state, server, nick) {
|
||||
if (!state[server]) {
|
||||
state[server] = [];
|
||||
}
|
||||
if (findIndex(state[server], n => n === nick) === -1) {
|
||||
state[server].push(nick);
|
||||
state[server] = sortBy(state[server], v => v.toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
export default createReducer(
|
||||
{},
|
||||
{
|
||||
[actions.OPEN_PRIVATE_CHAT](state, action) {
|
||||
open(state, action.server, action.nick);
|
||||
},
|
||||
|
||||
[actions.CLOSE_PRIVATE_CHAT](state, { server, nick }) {
|
||||
const i = findIndex(state[server], n => n === nick);
|
||||
if (i !== -1) {
|
||||
state[server].splice(i, 1);
|
||||
}
|
||||
},
|
||||
|
||||
[actions.socket.PM](state, action) {
|
||||
if (action.from.indexOf('.') === -1) {
|
||||
open(state, action.server, action.from);
|
||||
}
|
||||
},
|
||||
|
||||
[actions.DISCONNECT](state, { server }) {
|
||||
delete state[server];
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export function openPrivateChat(server, nick) {
|
||||
return {
|
||||
type: actions.OPEN_PRIVATE_CHAT,
|
||||
server,
|
||||
nick
|
||||
};
|
||||
}
|
||||
|
||||
export function closePrivateChat(server, nick) {
|
||||
return dispatch => {
|
||||
dispatch({
|
||||
type: actions.CLOSE_PRIVATE_CHAT,
|
||||
server,
|
||||
nick
|
||||
});
|
||||
dispatch(updateSelection());
|
||||
};
|
||||
}
|
38
client/js/state/search.js
Normal file
38
client/js/state/search.js
Normal file
|
@ -0,0 +1,38 @@
|
|||
import createReducer from 'utils/createReducer';
|
||||
import * as actions from './actions';
|
||||
|
||||
const initialState = {
|
||||
show: false,
|
||||
results: []
|
||||
};
|
||||
|
||||
export const getSearch = state => state.search;
|
||||
|
||||
export default createReducer(initialState, {
|
||||
[actions.socket.SEARCH](state, { results }) {
|
||||
state.results = results || [];
|
||||
},
|
||||
|
||||
[actions.TOGGLE_SEARCH](state) {
|
||||
state.show = !state.show;
|
||||
}
|
||||
});
|
||||
|
||||
export function searchMessages(server, channel, phrase) {
|
||||
return {
|
||||
type: actions.SEARCH_MESSAGES,
|
||||
server,
|
||||
channel,
|
||||
phrase,
|
||||
socket: {
|
||||
type: 'search',
|
||||
data: { server, channel, phrase }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function toggleSearch() {
|
||||
return {
|
||||
type: actions.TOGGLE_SEARCH
|
||||
};
|
||||
}
|
11
client/js/state/selectors.js
Normal file
11
client/js/state/selectors.js
Normal file
|
@ -0,0 +1,11 @@
|
|||
import { createSelector } from 'reselect';
|
||||
import get from 'lodash/get';
|
||||
import { getServers } from './servers';
|
||||
import { getSelectedTab } from './tab';
|
||||
|
||||
// eslint-disable-next-line import/prefer-default-export
|
||||
export const getSelectedTabTitle = createSelector(
|
||||
getSelectedTab,
|
||||
getServers,
|
||||
(tab, servers) => tab.name || get(servers, [tab.server, 'name'])
|
||||
);
|
210
client/js/state/servers.js
Normal file
210
client/js/state/servers.js
Normal file
|
@ -0,0 +1,210 @@
|
|||
import { createSelector } from 'reselect';
|
||||
import get from 'lodash/get';
|
||||
import createReducer from 'utils/createReducer';
|
||||
import { getSelectedTab, updateSelection } from './tab';
|
||||
import * as actions from './actions';
|
||||
|
||||
export const getServers = state => state.servers;
|
||||
|
||||
export const getCurrentNick = createSelector(
|
||||
getServers,
|
||||
getSelectedTab,
|
||||
(servers, tab) => {
|
||||
if (!servers[tab.server]) {
|
||||
return;
|
||||
}
|
||||
const { editedNick } = servers[tab.server];
|
||||
if (editedNick === null) {
|
||||
return servers[tab.server].nick;
|
||||
}
|
||||
return editedNick;
|
||||
}
|
||||
);
|
||||
|
||||
export const getCurrentServerName = createSelector(
|
||||
getServers,
|
||||
getSelectedTab,
|
||||
(servers, tab) => get(servers, [tab.server, 'name'])
|
||||
);
|
||||
|
||||
export const getCurrentServerStatus = createSelector(
|
||||
getServers,
|
||||
getSelectedTab,
|
||||
(servers, tab) => get(servers, [tab.server, 'status'], {})
|
||||
);
|
||||
|
||||
export default createReducer(
|
||||
{},
|
||||
{
|
||||
[actions.CONNECT](state, { host, nick, name }) {
|
||||
if (!state[host]) {
|
||||
state[host] = {
|
||||
nick,
|
||||
editedNick: null,
|
||||
name: name || host,
|
||||
status: {
|
||||
connected: false,
|
||||
error: null
|
||||
}
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
[actions.DISCONNECT](state, { server }) {
|
||||
delete state[server];
|
||||
},
|
||||
|
||||
[actions.SET_SERVER_NAME](state, { server, name }) {
|
||||
state[server].name = name;
|
||||
},
|
||||
|
||||
[actions.SET_NICK](state, { server, nick, editing }) {
|
||||
if (editing) {
|
||||
state[server].editedNick = nick;
|
||||
} else if (nick === '') {
|
||||
state[server].editedNick = null;
|
||||
}
|
||||
},
|
||||
|
||||
[actions.socket.NICK](state, { server, oldNick, newNick }) {
|
||||
if (!oldNick || oldNick === state[server].nick) {
|
||||
state[server].nick = newNick;
|
||||
state[server].editedNick = null;
|
||||
}
|
||||
},
|
||||
|
||||
[actions.socket.NICK_FAIL](state, { server }) {
|
||||
state[server].editedNick = null;
|
||||
},
|
||||
|
||||
[actions.socket.SERVERS](state, { data }) {
|
||||
if (data) {
|
||||
data.forEach(({ host, name, nick, status }) => {
|
||||
state[host] = { name, nick, status, editedNick: null };
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
[actions.socket.CONNECTION_UPDATE](state, { server, connected, error }) {
|
||||
if (state[server]) {
|
||||
state[server].status.connected = connected;
|
||||
state[server].status.error = error;
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export function connect(config) {
|
||||
return {
|
||||
type: actions.CONNECT,
|
||||
...config,
|
||||
socket: {
|
||||
type: 'connect',
|
||||
data: config
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function disconnect(server) {
|
||||
return dispatch => {
|
||||
dispatch({
|
||||
type: actions.DISCONNECT,
|
||||
server,
|
||||
socket: {
|
||||
type: 'quit',
|
||||
data: { server }
|
||||
}
|
||||
});
|
||||
dispatch(updateSelection());
|
||||
};
|
||||
}
|
||||
|
||||
export function reconnect(server, settings) {
|
||||
return {
|
||||
type: actions.RECONNECT,
|
||||
server,
|
||||
settings,
|
||||
socket: {
|
||||
type: 'reconnect',
|
||||
data: {
|
||||
...settings,
|
||||
server
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function whois(user, server) {
|
||||
return {
|
||||
type: actions.WHOIS,
|
||||
user,
|
||||
server,
|
||||
socket: {
|
||||
type: 'whois',
|
||||
data: { user, server }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function away(message, server) {
|
||||
return {
|
||||
type: actions.AWAY,
|
||||
message,
|
||||
server,
|
||||
socket: {
|
||||
type: 'away',
|
||||
data: { message, server }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function setNick(nick, server, editing) {
|
||||
nick = nick.trim().replace(' ', '');
|
||||
|
||||
const action = {
|
||||
type: actions.SET_NICK,
|
||||
nick,
|
||||
server,
|
||||
editing
|
||||
};
|
||||
|
||||
if (!editing && nick !== '') {
|
||||
action.socket = {
|
||||
type: 'nick',
|
||||
data: {
|
||||
newNick: nick,
|
||||
server
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return action;
|
||||
}
|
||||
|
||||
export function isValidServerName(name) {
|
||||
return name.trim() !== '';
|
||||
}
|
||||
|
||||
export function setServerName(name, server) {
|
||||
const action = {
|
||||
type: actions.SET_SERVER_NAME,
|
||||
name,
|
||||
server
|
||||
};
|
||||
|
||||
if (isValidServerName(name)) {
|
||||
action.socket = {
|
||||
type: 'set_server_name',
|
||||
data: {
|
||||
name,
|
||||
server
|
||||
},
|
||||
debounce: {
|
||||
delay: 500,
|
||||
key: `server_name:${server}`
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return action;
|
||||
}
|
127
client/js/state/settings.js
Normal file
127
client/js/state/settings.js
Normal file
|
@ -0,0 +1,127 @@
|
|||
import assign from 'lodash/assign';
|
||||
import createReducer from 'utils/createReducer';
|
||||
import * as actions from './actions';
|
||||
|
||||
export const getSettings = state => state.settings;
|
||||
|
||||
export default createReducer(
|
||||
{},
|
||||
{
|
||||
[actions.UPLOAD_CERT](state) {
|
||||
state.uploadingCert = true;
|
||||
},
|
||||
|
||||
[actions.socket.CERT_SUCCESS](state) {
|
||||
state.uploadingCert = false;
|
||||
delete state.certFile;
|
||||
delete state.cert;
|
||||
delete state.keyFile;
|
||||
delete state.key;
|
||||
},
|
||||
|
||||
[actions.socket.CERT_FAIL](state, action) {
|
||||
state.uploadingCert = false;
|
||||
state.certError = action.message;
|
||||
},
|
||||
|
||||
[actions.SET_CERT_ERROR](state, action) {
|
||||
state.uploadingCert = false;
|
||||
state.certError = action.message;
|
||||
},
|
||||
|
||||
[actions.SET_CERT](state, action) {
|
||||
state.certFile = action.fileName;
|
||||
state.cert = action.cert;
|
||||
},
|
||||
|
||||
[actions.SET_KEY](state, action) {
|
||||
state.keyFile = action.fileName;
|
||||
state.key = action.key;
|
||||
},
|
||||
|
||||
[actions.SETTINGS_SET](state, { key, value, settings }) {
|
||||
if (settings) {
|
||||
assign(state, settings);
|
||||
} else {
|
||||
state[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export function setCertError(message) {
|
||||
return {
|
||||
type: actions.SET_CERT_ERROR,
|
||||
message
|
||||
};
|
||||
}
|
||||
|
||||
export function uploadCert() {
|
||||
return (dispatch, getState) => {
|
||||
const { settings } = getState();
|
||||
if (settings.cert && settings.key) {
|
||||
dispatch({
|
||||
type: actions.UPLOAD_CERT,
|
||||
socket: {
|
||||
type: 'cert',
|
||||
data: {
|
||||
cert: settings.cert,
|
||||
key: settings.key
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
dispatch(setCertError('Missing certificate or key'));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function setCert(fileName, cert) {
|
||||
return {
|
||||
type: actions.SET_CERT,
|
||||
fileName,
|
||||
cert: cert
|
||||
};
|
||||
}
|
||||
|
||||
export function setKey(fileName, key) {
|
||||
return {
|
||||
type: actions.SET_KEY,
|
||||
fileName,
|
||||
key: key
|
||||
};
|
||||
}
|
||||
|
||||
export function setSetting(key, value) {
|
||||
return {
|
||||
type: actions.SETTINGS_SET,
|
||||
key,
|
||||
value,
|
||||
socket: {
|
||||
type: 'settings_set',
|
||||
data: {
|
||||
[key]: value
|
||||
},
|
||||
debounce: {
|
||||
delay: 250,
|
||||
key: `settings:${key}`
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function setSettings(settings, local = false) {
|
||||
const action = {
|
||||
type: actions.SETTINGS_SET,
|
||||
settings
|
||||
};
|
||||
|
||||
if (!local) {
|
||||
action.socket = {
|
||||
type: 'settings_set',
|
||||
data: settings
|
||||
};
|
||||
}
|
||||
|
||||
return action;
|
||||
}
|
84
client/js/state/tab.js
Normal file
84
client/js/state/tab.js
Normal file
|
@ -0,0 +1,84 @@
|
|||
import createReducer from 'utils/createReducer';
|
||||
import { push, replace, LOCATION_CHANGED } from 'utils/router';
|
||||
import * as actions from './actions';
|
||||
|
||||
const initialState = {
|
||||
selected: {},
|
||||
history: []
|
||||
};
|
||||
|
||||
function selectTab(state, action) {
|
||||
state.selected = {
|
||||
server: action.server,
|
||||
name: action.name
|
||||
};
|
||||
state.history.push(state.selected);
|
||||
}
|
||||
|
||||
export const getSelectedTab = state => state.tab.selected;
|
||||
|
||||
export default createReducer(initialState, {
|
||||
[actions.SELECT_TAB]: selectTab,
|
||||
|
||||
[actions.PART](state, action) {
|
||||
state.history = state.history.filter(
|
||||
tab => !(tab.server === action.server && tab.name === action.channels[0])
|
||||
);
|
||||
},
|
||||
|
||||
[actions.CLOSE_PRIVATE_CHAT](state, action) {
|
||||
state.history = state.history.filter(
|
||||
tab => !(tab.server === action.server && tab.name === action.nick)
|
||||
);
|
||||
},
|
||||
|
||||
[actions.DISCONNECT](state, action) {
|
||||
state.history = state.history.filter(tab => tab.server !== action.server);
|
||||
},
|
||||
|
||||
[LOCATION_CHANGED](state, action) {
|
||||
const { route, params } = action;
|
||||
if (route === 'chat') {
|
||||
selectTab(state, params);
|
||||
} else {
|
||||
state.selected = {};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export function select(server, name, doReplace) {
|
||||
const navigate = doReplace ? replace : push;
|
||||
if (name) {
|
||||
return navigate(`/${server}/${encodeURIComponent(name)}`);
|
||||
}
|
||||
return navigate(`/${server}`);
|
||||
}
|
||||
|
||||
export function updateSelection() {
|
||||
return (dispatch, getState) => {
|
||||
const state = getState();
|
||||
const { history } = state.tab;
|
||||
const { servers } = state;
|
||||
const { server } = state.tab.selected;
|
||||
const serverAddrs = Object.keys(servers);
|
||||
|
||||
if (serverAddrs.length === 0) {
|
||||
dispatch(replace('/connect'));
|
||||
} else if (history.length > 0) {
|
||||
const tab = history[history.length - 1];
|
||||
dispatch(select(tab.server, tab.name, true));
|
||||
} else if (servers[server]) {
|
||||
dispatch(select(server, null, true));
|
||||
} else {
|
||||
dispatch(select(serverAddrs.sort()[0], null, true));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function setSelectedTab(server, name = null) {
|
||||
return {
|
||||
type: actions.SELECT_TAB,
|
||||
server,
|
||||
name
|
||||
};
|
||||
}
|
46
client/js/state/ui.js
Normal file
46
client/js/state/ui.js
Normal file
|
@ -0,0 +1,46 @@
|
|||
import createReducer from 'utils/createReducer';
|
||||
import { LOCATION_CHANGED } from 'utils/router';
|
||||
import * as actions from './actions';
|
||||
|
||||
const initialState = {
|
||||
showTabList: false,
|
||||
showUserList: false
|
||||
};
|
||||
|
||||
export const getShowTabList = state => state.ui.showTabList;
|
||||
export const getShowUserList = state => state.ui.showUserList;
|
||||
|
||||
function setMenuHidden(state) {
|
||||
state.showTabList = false;
|
||||
}
|
||||
|
||||
export default createReducer(initialState, {
|
||||
[actions.TOGGLE_MENU](state) {
|
||||
state.showTabList = !state.showTabList;
|
||||
},
|
||||
|
||||
[actions.HIDE_MENU]: setMenuHidden,
|
||||
[LOCATION_CHANGED]: setMenuHidden,
|
||||
|
||||
[actions.TOGGLE_USERLIST](state) {
|
||||
state.showUserList = !state.showUserList;
|
||||
}
|
||||
});
|
||||
|
||||
export function hideMenu() {
|
||||
return {
|
||||
type: actions.HIDE_MENU
|
||||
};
|
||||
}
|
||||
|
||||
export function toggleMenu() {
|
||||
return {
|
||||
type: actions.TOGGLE_MENU
|
||||
};
|
||||
}
|
||||
|
||||
export function toggleUserList() {
|
||||
return {
|
||||
type: actions.TOGGLE_USERLIST
|
||||
};
|
||||
}
|
30
client/js/store.js
Normal file
30
client/js/store.js
Normal file
|
@ -0,0 +1,30 @@
|
|||
import { createStore, applyMiddleware, compose } from 'redux';
|
||||
import thunk from 'redux-thunk';
|
||||
import createReducer from 'state';
|
||||
import { routeReducer, routeMiddleware } from 'utils/router';
|
||||
import message from './middleware/message';
|
||||
import createSocketMiddleware from './middleware/socket';
|
||||
import commands from './commands';
|
||||
|
||||
export default function configureStore(socket) {
|
||||
/* eslint-disable no-underscore-dangle */
|
||||
const composeEnhancers =
|
||||
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
|
||||
|
||||
const reducer = createReducer(routeReducer);
|
||||
|
||||
const store = createStore(
|
||||
reducer,
|
||||
composeEnhancers(
|
||||
applyMiddleware(
|
||||
thunk,
|
||||
routeMiddleware,
|
||||
createSocketMiddleware(socket),
|
||||
message,
|
||||
commands
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
return store;
|
||||
}
|
6
client/js/sw.js
Normal file
6
client/js/sw.js
Normal file
|
@ -0,0 +1,6 @@
|
|||
workbox.skipWaiting();
|
||||
workbox.clientsClaim();
|
||||
|
||||
workbox.precaching.precacheAndRoute(self.__precacheManifest, {
|
||||
ignoreUrlParametersMatching: [/.*/]
|
||||
});
|
98
client/js/utils/Socket.js
Normal file
98
client/js/utils/Socket.js
Normal file
|
@ -0,0 +1,98 @@
|
|||
import Backoff from 'backo';
|
||||
|
||||
export default class Socket {
|
||||
constructor(host) {
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
this.url = `${protocol}://${host}/ws${window.location.pathname}`;
|
||||
|
||||
this.connectTimeout = 20000;
|
||||
this.pingTimeout = 30000;
|
||||
this.backoff = new Backoff({
|
||||
min: 1000,
|
||||
max: 5000,
|
||||
jitter: 0.25
|
||||
});
|
||||
this.handlers = [];
|
||||
this.connected = false;
|
||||
|
||||
this.connect();
|
||||
}
|
||||
|
||||
connect() {
|
||||
this.ws = new WebSocket(this.url);
|
||||
|
||||
this.timeoutConnect = setTimeout(() => {
|
||||
this.ws.close();
|
||||
this.retry();
|
||||
}, this.connectTimeout);
|
||||
|
||||
this.ws.onopen = () => {
|
||||
this.connected = true;
|
||||
this.emit('_connected', true);
|
||||
clearTimeout(this.timeoutConnect);
|
||||
this.backoff.reset();
|
||||
this.setTimeoutPing();
|
||||
};
|
||||
|
||||
this.ws.onclose = () => {
|
||||
if (this.connected) {
|
||||
this.connected = false;
|
||||
this.emit('_connected', false);
|
||||
}
|
||||
clearTimeout(this.timeoutConnect);
|
||||
clearTimeout(this.timeoutPing);
|
||||
if (!this.closing) {
|
||||
this.retry();
|
||||
}
|
||||
this.closing = false;
|
||||
};
|
||||
|
||||
this.ws.onerror = () => {
|
||||
clearTimeout(this.timeoutConnect);
|
||||
clearTimeout(this.timeoutPing);
|
||||
this.closing = true;
|
||||
this.ws.close();
|
||||
this.retry();
|
||||
};
|
||||
|
||||
this.ws.onmessage = e => {
|
||||
this.setTimeoutPing();
|
||||
|
||||
const msg = JSON.parse(e.data);
|
||||
|
||||
if (msg.type === 'ping') {
|
||||
this.send('pong');
|
||||
return;
|
||||
}
|
||||
|
||||
this.emit(msg.type, msg.data);
|
||||
};
|
||||
}
|
||||
|
||||
retry() {
|
||||
setTimeout(() => this.connect(), this.backoff.duration());
|
||||
}
|
||||
|
||||
send(type, data) {
|
||||
this.ws.send(JSON.stringify({ type, data }));
|
||||
}
|
||||
|
||||
setTimeoutPing() {
|
||||
clearTimeout(this.timeoutPing);
|
||||
this.timeoutPing = setTimeout(() => {
|
||||
this.closing = true;
|
||||
this.ws.close();
|
||||
this.connect();
|
||||
}, this.pingTimeout);
|
||||
}
|
||||
|
||||
onMessage(handler) {
|
||||
this.handlers.push(handler);
|
||||
}
|
||||
|
||||
emit(type, data) {
|
||||
for (let i = 0; i < this.handlers.length; i++) {
|
||||
this.handlers[i](type, data);
|
||||
}
|
||||
}
|
||||
}
|
120
client/js/utils/__tests__/util.test.js
Normal file
120
client/js/utils/__tests__/util.test.js
Normal file
|
@ -0,0 +1,120 @@
|
|||
import React from 'react';
|
||||
import TestRenderer from 'react-test-renderer';
|
||||
import { isChannel, isValidNick, isValidChannel, isValidUsername } from '..';
|
||||
import linkify from '../linkify';
|
||||
|
||||
const render = el => TestRenderer.create(el).toJSON();
|
||||
|
||||
describe('isChannel()', () => {
|
||||
it('it handles strings', () => {
|
||||
expect(isChannel('#cake')).toBe(true);
|
||||
expect(isChannel('cake')).toBe(false);
|
||||
});
|
||||
|
||||
it('handles tab objects', () => {
|
||||
expect(isChannel({ name: '#cake' })).toBe(true);
|
||||
expect(isChannel({ name: 'cake' })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isValidNick()', () => {
|
||||
it('validates nicks', () =>
|
||||
Object.entries({
|
||||
bob: true,
|
||||
'bob likes cake': false,
|
||||
'-bob': false,
|
||||
'bob.': false,
|
||||
'bob-': true,
|
||||
'1bob': false,
|
||||
'[bob}': true,
|
||||
'': false,
|
||||
' ': false
|
||||
}).forEach(([input, expected]) =>
|
||||
expect(isValidNick(input)).toBe(expected)
|
||||
));
|
||||
});
|
||||
|
||||
describe('isValidChannel()', () => {
|
||||
it('validates channels', () =>
|
||||
Object.entries({
|
||||
'#chan': true,
|
||||
'#cak e': false,
|
||||
'#cake:': false,
|
||||
'#[cake]': true,
|
||||
'#ca,ke': false,
|
||||
'': false,
|
||||
' ': false,
|
||||
cake: false
|
||||
}).forEach(([input, expected]) =>
|
||||
expect(isValidChannel(input)).toBe(expected)
|
||||
));
|
||||
|
||||
it('handles requirePrefix', () =>
|
||||
Object.entries({
|
||||
chan: true,
|
||||
'cak e': false,
|
||||
'#cake:': false,
|
||||
'#[cake]': true,
|
||||
'#ca,ke': false
|
||||
}).forEach(([input, expected]) =>
|
||||
expect(isValidChannel(input, false)).toBe(expected)
|
||||
));
|
||||
});
|
||||
|
||||
describe('isValidUsername()', () => {
|
||||
it('validates usernames', () =>
|
||||
Object.entries({
|
||||
bob: true,
|
||||
'bob likes cake': false,
|
||||
'-bob': true,
|
||||
'bob.': true,
|
||||
'bob-': true,
|
||||
'1bob': true,
|
||||
'[bob}': true,
|
||||
'': false,
|
||||
' ': false,
|
||||
'b@b': false
|
||||
}).forEach(([input, expected]) =>
|
||||
expect(isValidUsername(input)).toBe(expected)
|
||||
));
|
||||
});
|
||||
|
||||
describe('linkify()', () => {
|
||||
const proto = href => (href.indexOf('http') !== 0 ? `http://${href}` : href);
|
||||
const linkTo = href =>
|
||||
render(
|
||||
<a href={proto(href)} rel="noopener noreferrer" target="_blank">
|
||||
{href}
|
||||
</a>
|
||||
);
|
||||
|
||||
it('returns the arg when no matches are found', () =>
|
||||
[null, undefined, 10, false, true, 'just some text', ''].forEach(input =>
|
||||
expect(linkify(input)).toBe(input)
|
||||
));
|
||||
|
||||
it('linkifies text', () =>
|
||||
Object.entries({
|
||||
'google.com': linkTo('google.com'),
|
||||
'google.com stuff': [linkTo('google.com'), ' stuff'],
|
||||
'cake google.com stuff': ['cake ', linkTo('google.com'), ' stuff'],
|
||||
'cake google.com stuff https://google.com': [
|
||||
'cake ',
|
||||
linkTo('google.com'),
|
||||
' stuff ',
|
||||
linkTo('https://google.com')
|
||||
],
|
||||
'cake google.com stuff pie https://google.com ': [
|
||||
'cake ',
|
||||
linkTo('google.com'),
|
||||
' stuff pie ',
|
||||
linkTo('https://google.com'),
|
||||
' '
|
||||
],
|
||||
' google.com': [' ', linkTo('google.com')],
|
||||
'google.com ': [linkTo('google.com'), ' '],
|
||||
'/google.com?': ['/', linkTo('google.com'), '?']
|
||||
}).forEach(([input, expected]) =>
|
||||
expect(render(linkify(input))).toEqual(expected)
|
||||
));
|
||||
});
|
42
client/js/utils/color.js
Normal file
42
client/js/utils/color.js
Normal file
|
@ -0,0 +1,42 @@
|
|||
/* eslint-disable no-bitwise */
|
||||
import { hsluvToHex } from 'hsluv';
|
||||
|
||||
//
|
||||
// github.com/sindresorhus/fnv1a
|
||||
//
|
||||
const OFFSET_BASIS_32 = 2166136261;
|
||||
|
||||
const fnv1a = string => {
|
||||
let hash = OFFSET_BASIS_32;
|
||||
|
||||
for (let i = 0; i < string.length; i++) {
|
||||
hash ^= string.charCodeAt(i);
|
||||
|
||||
// 32-bit FNV prime: 2**24 + 2**8 + 0x93 = 16777619
|
||||
// Using bitshift for accuracy and performance. Numbers in JS suck.
|
||||
hash +=
|
||||
(hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
|
||||
}
|
||||
|
||||
return hash >>> 0;
|
||||
};
|
||||
|
||||
const colors = [];
|
||||
|
||||
for (let i = 0; i < 72; i++) {
|
||||
colors[i] = hsluvToHex([i * 5, 40, 50]);
|
||||
colors[i + 72] = hsluvToHex([i * 5, 70, 50]);
|
||||
colors[i + 144] = hsluvToHex([i * 5, 100, 50]);
|
||||
}
|
||||
|
||||
const cache = {};
|
||||
|
||||
export default function stringToRGB(str) {
|
||||
if (cache[str]) {
|
||||
return cache[str];
|
||||
}
|
||||
|
||||
const color = colors[fnv1a(str) % colors.length];
|
||||
cache[str] = color;
|
||||
return color;
|
||||
}
|
13
client/js/utils/connect.js
Normal file
13
client/js/utils/connect.js
Normal file
|
@ -0,0 +1,13 @@
|
|||
import { connect } from 'react-redux';
|
||||
|
||||
const strictEqual = (a, b) => a === b;
|
||||
|
||||
export default (mapState, mapDispatch) =>
|
||||
connect(
|
||||
mapState,
|
||||
mapDispatch,
|
||||
null,
|
||||
{
|
||||
areStatePropsEqual: strictEqual
|
||||
}
|
||||
);
|
11
client/js/utils/createReducer.js
Normal file
11
client/js/utils/createReducer.js
Normal file
|
@ -0,0 +1,11 @@
|
|||
import produce from 'immer';
|
||||
import has from 'lodash/has';
|
||||
|
||||
export default function createReducer(initialState, handlers) {
|
||||
return function reducer(state = initialState, action) {
|
||||
if (has(handlers, action.type)) {
|
||||
return produce(state, draft => handlers[action.type](draft, action));
|
||||
}
|
||||
return state;
|
||||
};
|
||||
}
|
189
client/js/utils/index.js
Normal file
189
client/js/utils/index.js
Normal file
|
@ -0,0 +1,189 @@
|
|||
import padStart from 'lodash/padStart';
|
||||
|
||||
export { findBreakpoints, messageHeight } from './messageHeight';
|
||||
export { default as linkify } from './linkify';
|
||||
|
||||
export function normalizeChannel(channel) {
|
||||
if (channel.indexOf('#') !== 0) {
|
||||
return channel;
|
||||
}
|
||||
|
||||
return channel
|
||||
.split('#')
|
||||
.join('')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
export function isChannel(name) {
|
||||
// TODO: Handle other channel types
|
||||
if (typeof name === 'object') {
|
||||
({ name } = name);
|
||||
}
|
||||
return typeof name === 'string' && name[0] === '#';
|
||||
}
|
||||
|
||||
export function stringifyTab(server, name) {
|
||||
if (typeof server === 'object') {
|
||||
if (server.name) {
|
||||
return `${server.server};${server.name}`;
|
||||
}
|
||||
return server.server;
|
||||
}
|
||||
if (name) {
|
||||
return `${server};${name}`;
|
||||
}
|
||||
return server;
|
||||
}
|
||||
|
||||
function isString(s, maxLength) {
|
||||
if (!s || typeof s !== 'string') {
|
||||
return false;
|
||||
}
|
||||
if (maxLength && s.length > maxLength) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// RFC 2812
|
||||
// nickname = ( letter / special ) *( letter / digit / special / "-" )
|
||||
// letter = A-Z / a-z
|
||||
// digit = 0-9
|
||||
// special = "[", "]", "\", "`", "_", "^", "{", "|", "}"
|
||||
export function isValidNick(nick, maxLength = 30) {
|
||||
if (!isString(nick, maxLength)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let i = 0; i < nick.length; i++) {
|
||||
const char = nick.charCodeAt(i);
|
||||
if (
|
||||
(i > 0 && char < 45) ||
|
||||
(char > 45 && char < 48) ||
|
||||
(char > 57 && char < 65) ||
|
||||
char > 125
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if ((i === 0 && char < 65) || char > 125) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// chanstring = any octet except NUL, BELL, CR, LF, " ", "," and ":"
|
||||
export function isValidChannel(channel, requirePrefix = true) {
|
||||
if (!isString(channel)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (requirePrefix && channel[0] !== '#') {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let i = 0; i < channel.length; i++) {
|
||||
const char = channel.charCodeAt(i);
|
||||
if (
|
||||
char === 0 ||
|
||||
char === 7 ||
|
||||
char === 10 ||
|
||||
char === 13 ||
|
||||
char === 32 ||
|
||||
char === 44 ||
|
||||
char === 58
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// user = any octet except NUL, CR, LF, " " and "@"
|
||||
export function isValidUsername(username) {
|
||||
if (!isString(username)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let i = 0; i < username.length; i++) {
|
||||
const char = username.charCodeAt(i);
|
||||
if (
|
||||
char === 0 ||
|
||||
char === 10 ||
|
||||
char === 13 ||
|
||||
char === 32 ||
|
||||
char === 64
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function isInt(i, min, max) {
|
||||
if (i < min || i > max || Math.floor(i) !== i) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function timestamp(date = new Date()) {
|
||||
const h = padStart(date.getHours(), 2, '0');
|
||||
const m = padStart(date.getMinutes(), 2, '0');
|
||||
return `${h}:${m}`;
|
||||
}
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
export function stringWidth(str, font) {
|
||||
ctx.font = font;
|
||||
return ctx.measureText(str).width;
|
||||
}
|
||||
|
||||
export function measureScrollBarWidth() {
|
||||
const outer = document.createElement('div');
|
||||
outer.style.visibility = 'hidden';
|
||||
outer.style.width = '100px';
|
||||
|
||||
document.body.appendChild(outer);
|
||||
|
||||
const widthNoScroll = outer.offsetWidth;
|
||||
outer.style.overflow = 'scroll';
|
||||
|
||||
const inner = document.createElement('div');
|
||||
inner.style.width = '100%';
|
||||
outer.appendChild(inner);
|
||||
|
||||
const widthWithScroll = inner.offsetWidth;
|
||||
|
||||
outer.parentNode.removeChild(outer);
|
||||
|
||||
return widthNoScroll - widthWithScroll;
|
||||
}
|
||||
|
||||
export function findIndex(arr, pred) {
|
||||
if (!arr) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
if (pred(arr[i])) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
export function find(arr, pred) {
|
||||
const i = findIndex(arr, pred);
|
||||
if (i !== -1) {
|
||||
return arr[i];
|
||||
}
|
||||
return null;
|
||||
}
|
67
client/js/utils/linkify.js
Normal file
67
client/js/utils/linkify.js
Normal file
|
@ -0,0 +1,67 @@
|
|||
import Autolinker from 'autolinker';
|
||||
import React from 'react';
|
||||
|
||||
const autolinker = new Autolinker({
|
||||
stripPrefix: false,
|
||||
stripTrailingSlash: false
|
||||
});
|
||||
|
||||
export default function linkify(text) {
|
||||
let matches = autolinker.parseText(text);
|
||||
|
||||
if (matches.length === 0) {
|
||||
return text;
|
||||
}
|
||||
|
||||
const result = [];
|
||||
let pos = 0;
|
||||
matches = autolinker.compactMatches(matches);
|
||||
|
||||
for (let i = 0; i < matches.length; i++) {
|
||||
const match = matches[i];
|
||||
|
||||
if (match.getType() === 'url') {
|
||||
if (match.offset > pos) {
|
||||
if (typeof result[result.length - 1] === 'string') {
|
||||
result[result.length - 1] += text.slice(pos, match.offset);
|
||||
} else {
|
||||
result.push(text.slice(pos, match.offset));
|
||||
}
|
||||
}
|
||||
|
||||
result.push(
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
href={match.getAnchorHref()}
|
||||
key={i}
|
||||
>
|
||||
{match.matchedText}
|
||||
</a>
|
||||
);
|
||||
} else if (typeof result[result.length - 1] === 'string') {
|
||||
result[result.length - 1] += text.slice(
|
||||
pos,
|
||||
match.offset + match.matchedText.length
|
||||
);
|
||||
} else {
|
||||
result.push(text.slice(pos, match.offset + match.matchedText.length));
|
||||
}
|
||||
|
||||
pos = match.offset + match.matchedText.length;
|
||||
}
|
||||
|
||||
if (pos < text.length) {
|
||||
if (typeof result[result.length - 1] === 'string') {
|
||||
result[result.length - 1] += text.slice(pos);
|
||||
} else {
|
||||
result.push(text.slice(pos));
|
||||
}
|
||||
}
|
||||
|
||||
if (result.length === 1) {
|
||||
return result[0];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
58
client/js/utils/messageHeight.js
Normal file
58
client/js/utils/messageHeight.js
Normal file
|
@ -0,0 +1,58 @@
|
|||
const lineHeight = 24;
|
||||
const userListWidth = 200;
|
||||
const smallScreen = 600;
|
||||
|
||||
export function findBreakpoints(text) {
|
||||
const breakpoints = [];
|
||||
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const char = text.charAt(i);
|
||||
|
||||
if (char === ' ') {
|
||||
breakpoints.push({ end: i, next: i + 1 });
|
||||
} else if (char === '-' && i !== text.length - 1) {
|
||||
breakpoints.push({ end: i + 1, next: i + 1 });
|
||||
}
|
||||
}
|
||||
|
||||
return breakpoints;
|
||||
}
|
||||
|
||||
export function messageHeight(
|
||||
message,
|
||||
wrapWidth,
|
||||
charWidth,
|
||||
indent = 0,
|
||||
windowWidth
|
||||
) {
|
||||
let pad = (6 + (message.from ? message.from.length + 1 : 0)) * charWidth;
|
||||
let height = lineHeight + 8;
|
||||
|
||||
if (message.channel && windowWidth > smallScreen) {
|
||||
wrapWidth -= userListWidth;
|
||||
}
|
||||
|
||||
if (pad + message.length * charWidth < wrapWidth) {
|
||||
return height;
|
||||
}
|
||||
|
||||
const breaks = message.breakpoints;
|
||||
let prevBreak = 0;
|
||||
let prevPos = 0;
|
||||
|
||||
for (let i = 0; i < breaks.length; i++) {
|
||||
if (pad + (breaks[i].end - prevBreak) * charWidth >= wrapWidth) {
|
||||
prevBreak = prevPos;
|
||||
pad = indent;
|
||||
height += lineHeight;
|
||||
}
|
||||
|
||||
prevPos = breaks[i].next;
|
||||
}
|
||||
|
||||
if (pad + (message.length - prevBreak) * charWidth >= wrapWidth) {
|
||||
height += lineHeight;
|
||||
}
|
||||
|
||||
return height;
|
||||
}
|
111
client/js/utils/observe.js
Normal file
111
client/js/utils/observe.js
Normal file
|
@ -0,0 +1,111 @@
|
|||
function subscribeArray(store, selectors, handler, init) {
|
||||
let state = store.getState();
|
||||
let prev = selectors.map(selector => selector(state));
|
||||
if (init) {
|
||||
handler(...prev);
|
||||
}
|
||||
|
||||
return store.subscribe(() => {
|
||||
state = store.getState();
|
||||
const next = [];
|
||||
let changed = false;
|
||||
|
||||
for (let i = 0; i < selectors.length; i++) {
|
||||
next[i] = selectors[i](state);
|
||||
if (next[i] !== prev[i]) {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
handler(...next);
|
||||
prev = next;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function subscribe(store, selector, handler, init) {
|
||||
if (Array.isArray(selector)) {
|
||||
return subscribeArray(store, selector, handler, init);
|
||||
}
|
||||
|
||||
let prev = selector(store.getState());
|
||||
if (init) {
|
||||
handler(prev);
|
||||
}
|
||||
|
||||
return store.subscribe(() => {
|
||||
const next = selector(store.getState());
|
||||
if (next !== prev) {
|
||||
handler(next);
|
||||
prev = next;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Handler gets called every time the selector(s) change
|
||||
//
|
||||
export function observe(store, selector, handler) {
|
||||
return subscribe(store, selector, handler, true);
|
||||
}
|
||||
|
||||
//
|
||||
// Handler gets called once the next time the selector(s) change
|
||||
//
|
||||
export function once(store, selector, handler) {
|
||||
let done = false;
|
||||
const unsubscribe = subscribe(store, selector, (...args) => {
|
||||
if (!done) {
|
||||
done = true;
|
||||
handler(...args);
|
||||
}
|
||||
unsubscribe();
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Handler gets called once when the predicate returns true, the predicate gets passed
|
||||
// the result of the selector(s), if no predicate is set it defaults to checking if the
|
||||
// selector(s) return something truthy
|
||||
//
|
||||
export function when(store, selector, predicate, handler) {
|
||||
if (arguments.length === 3) {
|
||||
handler = predicate;
|
||||
|
||||
if (Array.isArray(selector)) {
|
||||
predicate = (...args) => {
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (!args[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
} else {
|
||||
predicate = o => o;
|
||||
}
|
||||
}
|
||||
|
||||
const state = store.getState();
|
||||
if (Array.isArray(selector)) {
|
||||
const val = selector.map(s => s(state));
|
||||
if (predicate(...val)) {
|
||||
return handler(...val);
|
||||
}
|
||||
} else {
|
||||
const val = selector(state);
|
||||
if (predicate(val)) {
|
||||
return handler(val);
|
||||
}
|
||||
}
|
||||
|
||||
let done = false;
|
||||
const unsubscribe = subscribe(store, selector, (...args) => {
|
||||
if (!done && predicate(...args)) {
|
||||
done = true;
|
||||
handler(...args);
|
||||
}
|
||||
unsubscribe();
|
||||
});
|
||||
}
|
110
client/js/utils/router.js
Normal file
110
client/js/utils/router.js
Normal file
|
@ -0,0 +1,110 @@
|
|||
import createHistory from 'history/createBrowserHistory';
|
||||
import UrlPattern from 'url-pattern';
|
||||
|
||||
const history = createHistory();
|
||||
|
||||
export const LOCATION_CHANGED = 'ROUTER_LOCATION_CHANGED';
|
||||
export const PUSH = 'ROUTER_PUSH';
|
||||
export const REPLACE = 'ROUTER_REPLACE';
|
||||
|
||||
export function locationChanged(route, params, location) {
|
||||
return {
|
||||
type: LOCATION_CHANGED,
|
||||
route,
|
||||
params,
|
||||
location
|
||||
};
|
||||
}
|
||||
|
||||
export function push(path) {
|
||||
return {
|
||||
type: PUSH,
|
||||
path
|
||||
};
|
||||
}
|
||||
|
||||
export function replace(path) {
|
||||
return {
|
||||
type: REPLACE,
|
||||
path
|
||||
};
|
||||
}
|
||||
|
||||
export function routeReducer(state = {}, action) {
|
||||
if (action.type === LOCATION_CHANGED) {
|
||||
return {
|
||||
route: action.route,
|
||||
params: action.params,
|
||||
location: action.location
|
||||
};
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
export function routeMiddleware() {
|
||||
return next => action => {
|
||||
switch (action.type) {
|
||||
case PUSH:
|
||||
history.push(action.path);
|
||||
break;
|
||||
case REPLACE:
|
||||
history.replace(action.path);
|
||||
break;
|
||||
default:
|
||||
return next(action);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function decode(location) {
|
||||
location.pathname = decodeURIComponent(location.pathname);
|
||||
return location;
|
||||
}
|
||||
|
||||
function match(routes, location) {
|
||||
let params;
|
||||
for (let i = 0; i < routes.length; i++) {
|
||||
params = routes[i].pattern.match(location.pathname);
|
||||
if (params !== null) {
|
||||
const keys = Object.keys(params);
|
||||
for (let j = 0; j < keys.length; j++) {
|
||||
params[keys[j]] = decodeURIComponent(params[keys[j]]);
|
||||
}
|
||||
return locationChanged(routes[i].name, params, decode(location));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function initRouter(routes, store) {
|
||||
const patterns = [];
|
||||
const opts = {
|
||||
segmentValueCharset: 'a-zA-Z0-9-_.%'
|
||||
};
|
||||
|
||||
Object.keys(routes).forEach(name =>
|
||||
patterns.push({
|
||||
name,
|
||||
pattern: new UrlPattern(routes[name], opts)
|
||||
})
|
||||
);
|
||||
|
||||
let matched = match(patterns, history.location);
|
||||
if (matched) {
|
||||
store.dispatch(matched);
|
||||
} else {
|
||||
matched = { location: {} };
|
||||
}
|
||||
|
||||
history.listen(location => {
|
||||
const nextMatch = match(patterns, location);
|
||||
if (
|
||||
nextMatch &&
|
||||
nextMatch.location.pathname !== matched.location.pathname
|
||||
) {
|
||||
matched = nextMatch;
|
||||
store.dispatch(matched);
|
||||
}
|
||||
});
|
||||
}
|
12
client/js/utils/scrollPosition.js
Normal file
12
client/js/utils/scrollPosition.js
Normal file
|
@ -0,0 +1,12 @@
|
|||
const positions = {};
|
||||
|
||||
export function getScrollPos(key) {
|
||||
if (key in positions) {
|
||||
return positions[key];
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
export function saveScrollPos(key, pos) {
|
||||
positions[key] = pos;
|
||||
}
|
45
client/js/utils/size.js
Normal file
45
client/js/utils/size.js
Normal file
|
@ -0,0 +1,45 @@
|
|||
let width, height;
|
||||
const listeners = [];
|
||||
|
||||
function update() {
|
||||
width = window.innerWidth;
|
||||
height = window.innerHeight;
|
||||
|
||||
for (let i = 0; i < listeners.length; i++) {
|
||||
listeners[i](width, height);
|
||||
}
|
||||
}
|
||||
|
||||
let resizeRAF;
|
||||
|
||||
function resize() {
|
||||
if (resizeRAF) {
|
||||
window.cancelAnimationFrame(resizeRAF);
|
||||
}
|
||||
resizeRAF = window.requestAnimationFrame(update);
|
||||
}
|
||||
|
||||
update();
|
||||
window.addEventListener('resize', resize);
|
||||
|
||||
export function windowWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
export function windowHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
export function addResizeListener(f, init) {
|
||||
listeners.push(f);
|
||||
if (init) {
|
||||
f(width, height);
|
||||
}
|
||||
}
|
||||
|
||||
export function removeResizeListener(f) {
|
||||
const i = listeners.indexOf(f);
|
||||
if (i > -1) {
|
||||
listeners.splice(i, 1);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue