256 Commits
v0.4 ... v0.7

Author SHA1 Message Date
08ffc79a65 Remove local messages when closing dm tab, avoid sending open_dm if already open 2020-05-08 02:56:54 +02:00
2a72b198e3 Update dependencies 2020-05-08 02:10:22 +02:00
0d085a2b4d Clear prevSearch when closing modal 2020-05-07 08:10:25 +02:00
497f9e882c Unvendor fnv1a 2020-05-06 06:50:53 +02:00
7d97d10e76 Open dm tab on /msg 2020-05-06 04:50:27 +02:00
8305dd561d Log direct messages and keep track of open direct message tabs 2020-05-06 04:19:55 +02:00
e97bb519ed Merge pull request #61 from nhandler/patch-1
Replace Freenode with freenode
2020-05-05 07:26:38 +02:00
18acde5b2b Replace Freenode with freenode in test
The freenode IRC network brands itself with a lowercase `f`.
2020-05-04 21:37:39 -07:00
bab4732221 Replace Freenode with freenode in default config
The freenode IRC network brands itself with a lowercase `f`.
2020-05-04 21:36:21 -07:00
79af695d17 Add apple-touch-icon 2020-05-05 03:34:36 +02:00
d98312f99b Cache manifest.json 2020-05-05 03:31:14 +02:00
010bb6a102 Sleep before first reconnect attempt 2020-05-05 01:35:05 +02:00
530e08b9ee Convert withModal to useModal 2020-05-03 09:05:16 +02:00
9cf42df1ea Remove channel from reconnect list when parting 2020-05-01 05:40:49 +02:00
b81e1e482a Add auth config struct and restructure social auth provider config to enable iteration and adding other providers 2020-05-01 04:35:26 +02:00
3d7011e504 Add vscode to config command editor stack and enable passing in an arbitrary editor 2020-05-01 04:31:20 +02:00
3d2e443108 Pass all unknown commands through to the IRC server, closes #56 2020-05-01 02:12:21 +02:00
b002eef285 Fix navicon 2020-04-30 14:36:30 +02:00
c566d5d61d Copy location object 2020-04-30 13:44:36 +02:00
13a31c30d9 Update .goreleaser.yml 2020-04-30 08:16:06 +02:00
508a41ee45 Update client dependencies 2020-04-30 07:54:30 +02:00
1794e2680a Update server dependencies 2020-04-29 04:23:32 +02:00
c704ebb042 Use react-icons 2020-04-29 03:13:35 +02:00
bb66740fd1 Update gulp instructions in README 2020-04-24 03:04:46 +02:00
4010132884 Linkify topics in channel joining modal 2020-04-24 02:37:56 +02:00
77543e3aed Switch to bbolt 2020-04-23 01:06:36 +02:00
360bed00f9 Implement old storage.Path API 2020-04-20 03:02:15 +02:00
164e071e7f Update README 2020-04-20 02:15:57 +02:00
01914f070d Turn modules off when installing go-bindata on travis 2020-04-20 02:07:12 +02:00
00e40dc153 Update go.mod and modules.txt format 2020-04-20 01:38:06 +02:00
47efab2e56 Update .travis.yml 2020-04-20 01:27:25 +02:00
c171a620e0 Merge pull request #58 from daftaupe/configpath
Allow dispatch to store data and configuration separately
2020-04-19 20:30:34 +02:00
ca81475fa5 Add option --config and --data to specify where to store the configuration and the data 2020-03-20 18:24:17 +01:00
52b2b6677f Merge pull request #50 from khlieng/dependabot/npm_and_yarn/client/eslint-utils-1.4.3
Bump eslint-utils from 1.3.1 to 1.4.3 in /client
2019-10-31 22:37:03 +01:00
5013ab6db1 Bump eslint-utils from 1.3.1 to 1.4.3 in /client
Bumps [eslint-utils](https://github.com/mysticatea/eslint-utils) from 1.3.1 to 1.4.3.
- [Release notes](https://github.com/mysticatea/eslint-utils/releases)
- [Commits](https://github.com/mysticatea/eslint-utils/compare/v1.3.1...v1.4.3)

Signed-off-by: dependabot[bot] <support@github.com>
2019-10-31 10:55:29 +00:00
855f4d3e64 Stop using pointers for nested config structs, closes #41 2019-06-09 02:29:35 +02:00
540efa03c4 Update dependencies 2019-06-09 02:01:48 +02:00
7ad76273c0 Fix MessageBox scroll stutter when state updates while close to the bottom 2019-02-08 09:28:55 +01:00
c1e1f2c327 Update dependencies 2019-02-08 09:10:06 +01:00
4eda7ef396 Fix getSortedChannels test 2019-02-08 08:56:21 +01:00
fad2e030d4 Fix h2 push hash check 2019-02-01 06:39:38 +01:00
3e90e6c86d Only count joined channels 2019-01-30 04:48:37 +01:00
71bfe92dae Update dependencies 2019-01-30 03:51:13 +01:00
613d9fca6e Send irc features to the client 2019-01-27 08:53:07 +01:00
9267c661dc Timeout channel list updates 2019-01-25 11:24:57 +01:00
f8e12f5938 Handle channel forwarding and errors better 2019-01-25 11:02:31 +01:00
497934888c Fix channel reducer tests 2019-01-25 08:36:21 +01:00
24960f23b9 Add topic modal 2019-01-25 03:57:58 +01:00
aab1ad3e99 Fix h2 push 2019-01-25 02:32:22 +01:00
815b518c2c Update dependencies 2019-01-23 08:52:17 +01:00
5e674254f0 Use pointer receiver in stateData 2019-01-23 08:20:16 +01:00
24b26aa85f Add channel joining UI, closes #37 2019-01-23 07:34:39 +01:00
f25594e962 Add casefolding to irc lib 2019-01-13 05:10:11 +01:00
075e404079 Reset backoff on RPL_WELCOME 2019-01-11 05:00:15 +01:00
eee260f154 Read lines with a bufio.Scanner, reuse input buffer, ignore empty messages, handle multiple spaces between tags and prefix 2019-01-11 04:53:50 +01:00
a3618b97ae Add list command 2019-01-11 02:46:46 +01:00
e4d5d2737b Use strings.Replacer to unescape tags 2019-01-11 02:19:57 +01:00
0085cea5a1 Add react-modal, replace confirm usage with it 2019-01-05 07:08:34 +01:00
63cf65100d Pull https handling out into a new package 2018-12-31 03:33:05 +01:00
67e32661f1 Update dependencies 2018-12-31 02:20:22 +01:00
95eff71e2e Add go 1.12beta1 travis build 2018-12-21 01:53:35 +01:00
8526805c2f Add headers config, closes #25 2018-12-20 11:51:31 +01:00
6aaa2b521d Avoid sending join when the channels input is empty 2018-12-19 03:09:13 +01:00
0d9290d037 Update client dependencies 2018-12-19 02:55:50 +01:00
6fedb23363 Prerender index page 2018-12-17 14:44:46 +01:00
fc643483be Dont redirect private IPs and localhost 2018-12-17 12:45:33 +01:00
6c3a5777c4 Use certmagic, simplify config, set HTTP timeouts and a modern TLSConfig 2018-12-16 12:32:03 +01:00
c5a9a5b1c1 Print go version 2018-12-15 11:30:29 +01:00
6a816fbff6 Add date marker tests 2018-12-15 11:20:49 +01:00
3c105c493b Handle messages with no content, improve prepend perf 2018-12-15 11:09:57 +01:00
50d735aaa3 Add date markers 2018-12-14 14:24:23 +01:00
34d89c75b2 Use correct gulp version on travis 2018-12-11 11:17:05 +01:00
71f79fd84e Pass in config struct 2018-12-11 10:54:05 +01:00
8f1105bc59 Only attempt to maintain scroll position when prepending messages if there was previously any messages 2018-12-08 11:56:02 +01:00
0e46fbcc82 Clean up initialState module 2018-12-08 11:25:08 +01:00
c1ca29511e Simplify routing logic 2018-12-08 11:08:01 +01:00
35c2d682e3 Improve routing 2018-12-07 08:48:40 +01:00
aca380629f Update dotfiles 2018-12-06 11:05:10 +01:00
007fc80e72 Update dependencies 2018-12-06 11:03:03 +01:00
cca3f5bc93 Use stable readme download links 2018-12-02 11:31:35 +01:00
f05e405fb1 Embed version info in docker build 2018-12-02 07:39:23 +01:00
73205b64f6 v0.5.4 2018-11-29 13:07:27 +01:00
5861a54dfc Improve 404 handling 2018-11-29 13:06:37 +01:00
869713d236 Fix initial scroll position sometimes being off 2018-11-29 12:05:42 +01:00
0438a099cf Fix dev mode, turn off react concurrent mode, update dependencies 2018-11-29 11:54:05 +01:00
df71c54d37 Use a map to serve files 2018-11-27 12:07:48 +01:00
d24d33d94c Fix push cookie hash check 2018-11-27 11:34:02 +01:00
57704c9e89 v0.5.3 2018-11-26 02:09:29 +01:00
dd03e75be4 Add amd64 and darwin archive name replacements 2018-11-26 02:07:41 +01:00
4eac0609c2 Add bottom margin to settings version 2018-11-26 02:05:21 +01:00
bf2e7875a5 Add version flags and command, closes #38 2018-11-26 01:58:24 +01:00
fbbcf6457e Show version info in settings 2018-11-22 12:08:18 +01:00
5d896ae439 Print prettier version info 2018-11-22 11:31:02 +01:00
9b40934654 Grab referer in /init handler instead of getIndexData() 2018-11-22 10:40:29 +01:00
bd0541120f Improve document.title handling 2018-11-22 10:09:13 +01:00
09a1933131 Increase scrollbackDebounce to 150 2018-11-22 09:51:26 +01:00
8eb1f9cbb4 Fix some messages not rendering on MessageBox mount, handle scroll restoration edge case 2018-11-22 09:50:38 +01:00
9ca50b1546 v0.5.2 2018-11-22 08:48:29 +01:00
0699fc287d Fix scroll jumping on MessageBox mount 2018-11-22 08:48:29 +01:00
937480bfd4 Prevent rounded input corners in Safari 2018-11-22 08:48:29 +01:00
05527e41b7 Use absolute paths 2018-11-22 08:48:29 +01:00
65e103fd23 Delete release.sh 2018-11-21 02:17:51 +01:00
2a7b7572fa Update readme download links 2018-11-17 12:48:15 +01:00
2c1a6f2c44 Discard git changes when doing a release on travis 2018-11-17 12:34:12 +01:00
96f18117bd v0.5.1 2018-11-17 12:22:28 +01:00
90785aba20 Create sessions on boot requests instead of websocket handshakes 2018-11-17 11:52:36 +01:00
da87dccb53 Update react-hot-loader to 4.4.0, turn on pureSFC 2018-11-17 11:12:30 +01:00
b54cb42426 Setup goreleaser 2018-11-17 10:32:02 +01:00
4dcf674c4b Add robots.txt, clean up index template 2018-11-14 10:11:15 +01:00
764475b2a5 Turn on terserOptions.safari10 2018-11-14 09:24:40 +01:00
d867ca8477 Add worker-src csp directive 2018-11-14 08:34:35 +01:00
a783a87d04 Set overscanCount to 5 2018-11-14 08:33:01 +01:00
a7b6442ed9 Update dependencies 2018-11-14 08:25:20 +01:00
374604fae2 v0.5 2018-11-11 07:08:53 +01:00
48f59604a6 Update readme lib list 2018-11-10 12:56:31 +01:00
474afda9c2 Add manifest.json, icons and install button, flatten client/src 2018-11-10 12:33:44 +01:00
a219e689c1 Update vendor dir 2018-11-10 08:04:36 +01:00
9c9b05d479 Update react-redux to 6.0.0-beta.2, enable react concurrent mode, use strict equality mapState checks 2018-11-09 08:11:01 +01:00
04852cdf58 Implement http.Handler in server.Dispatch 2018-11-09 07:32:47 +01:00
4b4b2394a9 Link rel preload boot data 2018-11-09 07:12:43 +01:00
9b6844449d Vendor workbox 2018-11-08 09:39:32 +01:00
9a5d7f8360 Exclude inline chunks from precache manifest 2018-11-08 08:57:24 +01:00
70b2c4df47 Dont refresh session keys on bootloader requests 2018-11-08 08:39:47 +01:00
f86e0d9283 Dont do auth on service worker index page requests 2018-11-07 02:55:00 +01:00
fd6c8a70e2 Append pathname to bootloader request 2018-11-07 02:07:23 +01:00
ed40b956b7 Set publicPath in production webpack config 2018-11-07 01:35:53 +01:00
ca222ff10d Add cache-first service worker 2018-11-06 11:13:32 +01:00
b2b5f82486 Shallow render linkify test 2018-11-05 08:23:22 +01:00
69d5f41270 Fix message rendering 2018-11-05 07:11:15 +01:00
d930365eeb Code split the client, update dependencies 2018-11-04 07:23:07 +01:00
84c3d5cc88 Merge pull request #35 from diadara/patch-2
Update readme
2018-11-01 22:06:19 +01:00
ef34baf5a0 Update readme
Make instructions for starting dev environment explicit
2018-10-31 15:49:41 +07:00
38ed5a367b Make sure list has mounted before using ref 2018-10-26 08:18:31 +02:00
4482dd33ce Migrate from react-virtualized to react-window 2018-10-26 07:00:37 +02:00
675e350da3 Use Cache-Control immutable and SameSite Lax 2018-10-19 02:11:12 +02:00
7658e3bde7 Avoid dispatching unneeded socket actions 2018-10-16 01:04:49 +02:00
7fb0cd3e6a Send default settings when there is no user yet 2018-10-15 09:06:43 +02:00
6c6a9e12cf Add colored nicks settings option 2018-10-15 08:56:17 +02:00
ec03db4db6 Remove base64-arraybuffer 2018-10-10 21:23:42 +02:00
afc80650e7 Use HSLuv for nick colors 2018-10-08 01:34:53 +02:00
6146b27adc Update readme 2018-10-07 01:27:26 +02:00
973aa3b104 Bust dat screenshot cache 2018-10-07 01:15:09 +02:00
6f6dfca5fb Move "Add network" button down 2018-10-07 01:13:58 +02:00
b3f2b53a6f Add colored nicks 2018-10-07 00:25:56 +02:00
937987da82 Drop go 1.9 support 2018-10-06 09:17:59 +02:00
91fd50fe10 Make gen:install work outside GOPATH 2018-10-06 09:15:11 +02:00
3ec450805b Set SameSite Strict on session cookies 2018-10-06 08:56:29 +02:00
09de41c0a2 Use ErrorMessage component 2018-10-06 08:46:28 +02:00
66bf957460 Update dependencies 2018-10-06 08:09:29 +02:00
ccdd56fea4 Explicitly set input background color 2018-09-24 01:10:21 +02:00
963e36c296 Preload fonts 2018-09-18 22:09:08 +02:00
1de1d1473d Drop go 1.8 support 2018-08-31 04:09:07 +02:00
47bc78b80a Update all dependencies 2018-08-31 03:57:19 +02:00
628dc66685 Go modules! 2018-08-31 03:08:17 +02:00
b0b3489e15 Update go version on travis 2018-08-23 22:03:48 +02:00
5defd315f1 Merge pull request #33 from daftaupe/#17
Change Connect button to Add Network
2018-08-23 12:27:49 +02:00
2db878d2cb Change Connect button to Add Network
Signed-off-by: Pierre-Alain TORET <pierre-alain.toret@protonmail.com>
2018-08-23 11:01:44 +02:00
0b49df6bcf Merge pull request #32 from daftaupe/#31
Add command line option for server binding
2018-08-22 15:53:34 +02:00
bd46082cfe Add command line option for server binding
Signed-off-by: Pierre-Alain TORET <pierre-alain.toret@protonmail.com>
2018-08-22 09:16:44 +02:00
508969e189 Update client dependencies 2018-08-22 00:53:45 +02:00
3dea4d6513 Add go 1.11rc1 travis build 2018-08-22 00:36:28 +02:00
c8c09bce8c Add option to choose which address to listen on, closes #31 2018-08-22 00:31:29 +02:00
004e7890e5 Update client dependencies 2018-08-12 23:28:58 +02:00
f20ca4038e Fix connect form readonly casing 2018-08-10 21:35:37 +02:00
1406b87d77 Fix checkbox 2018-08-10 21:30:44 +02:00
c975c5d120 Add option to hex encode the source IP of a client and use it as the ident, closes #24 2018-08-10 21:02:09 +02:00
e2c6cedc27 Merge pull request #30 from daftaupe/#26
Add support for X-Forwarded-For
2018-07-25 00:18:29 +02:00
8ed27bf54b Add support for X-Forwarded-For 2018-07-24 22:01:01 +02:00
a4d2cf17aa Hide original checkbox better 2018-06-20 17:31:59 +02:00
fb287dce2f Fix tests 2018-06-18 16:12:19 +02:00
352f7a8487 Merge pull request #23 from EdwardBetts/spelling
Correct spelling mistakes.
2018-06-18 15:59:17 +02:00
ad238726b7 Correct spelling mistakes. 2018-06-18 14:47:51 +01:00
8f20593b26 Create root directory explicitly, closes #22 2018-06-17 23:47:47 +02:00
fde6a9e630 Wait 15 seconds before reconnecting if the connection closed before registration finished 2018-06-17 22:53:22 +02:00
9669092148 Fix horizontal overflow 2018-06-10 21:35:12 +02:00
3d2dbd5527 Add custom checkbox 2018-06-10 21:25:58 +02:00
b07d1eb871 Update client dependencies 2018-06-07 23:12:09 +02:00
d2c1297cf7 Scroll text inputs into view, use red labels in text inputs when theres an error, only autocapitalize the name field 2018-06-03 06:18:03 +02:00
f5de115534 Remove TTF fonts 2018-06-01 22:10:20 +02:00
494dbc4cf5 Remove session expiration timer 2018-06-01 05:59:13 +02:00
c49bbc72d4 Do all session pruning in a single goroutine 2018-06-01 05:40:12 +02:00
e8f5809940 Do session disk writes in a new goroutine 2018-06-01 04:47:11 +02:00
e0200a2b2a Name all storage interface params, return slices of pointers 2018-06-01 04:16:38 +02:00
09248edd59 Fix irc handler tests 2018-06-01 03:37:22 +02:00
24f9553aa5 Persist, renew and delete sessions, refactor storage package, move reusable packages to pkg 2018-05-31 23:24:59 +02:00
121582f72a Update client dependencies 2018-05-31 23:23:01 +02:00
70322c2e43 Add Sauce Labs credit 2018-05-30 04:42:32 +02:00
9529af55c7 Update prettier to 1.13.0 2018-05-28 03:16:05 +02:00
21b6740e8b Update client dependencies 2018-05-26 00:04:11 +02:00
09d57b7023 Use easyjson 2018-05-25 23:54:36 +02:00
e7cff1686e Clean up some things 2018-05-25 04:12:02 +02:00
e2a895a1b9 Autoprefix css in development 2018-05-25 03:27:53 +02:00
b4c9338772 Change browserslist 2018-05-25 03:26:41 +02:00
637f0d956b Wait until a websocket connection comes in before creating new anonymous sessions 2018-05-22 03:57:52 +02:00
27653982d7 Delete docker.sh 2018-05-19 01:02:50 +02:00
2f2c500453 Use correct ssl property name, closes #14 2018-05-18 05:33:33 +02:00
d27d108a07 Make sure the connect form port is always a string 2018-05-18 05:13:25 +02:00
4ac0dd7c4b Handle default port properly, closes #18 2018-05-18 04:15:20 +02:00
b09da1fc3b Merge pull request #16 from prologic/consistency_config_options
Makes configuration options consistent
2018-05-18 03:50:31 +02:00
2ada552220 Validate port numbers better 2018-05-18 03:39:40 +02:00
16ce3cdfa5 Make configuration options consistent 2018-05-17 18:37:33 -07:00
9806d6c12f Use nick as username and realname if they are missing 2018-05-18 03:14:22 +02:00
8f8adc37e7 Update react-virtualized to 9.19.0 2018-05-18 02:38:58 +02:00
ed0c413542 Merge pull request #12 from prologic/improved_dockerfile
Improved Dockerfile to properly build and ship a runtime image
2018-05-18 00:58:22 +02:00
276d8f7849 Improved Dockerfile to properly build and ship a runtime image 2018-05-17 15:44:15 -07:00
6fd5235ec9 Add new connect form, closes #7 2018-05-16 05:02:48 +02:00
f502fea5c1 Update client dependencies 2018-05-16 05:01:31 +02:00
abc495f849 Update README 2018-05-16 03:54:19 +02:00
4fafe2b158 Update gulp to 4.0.0 2018-05-16 03:46:42 +02:00
29a225ed13 Make it run better in IE11 2018-05-06 21:36:05 +02:00
91e5556c86 Make it run in IE11 2018-05-05 21:54:00 +02:00
de36fe682a Update server dependencies 2018-05-04 23:39:27 +02:00
fb8fec38ff Use correct hash length when reading the push cookie 2018-04-30 22:53:29 +02:00
d4d03eac12 Add promise polyfill 2018-04-30 22:41:12 +02:00
33e0f67766 Add IRCv3 tag parsing 2018-04-29 03:49:02 +02:00
62e115498f Deal with empty ISUPPORT param names 2018-04-29 02:13:22 +02:00
f2504cc245 Add RPL_ISUPPORT parsing 2018-04-28 20:31:44 +02:00
735f96d3b1 Remove unused eslint rule 2018-04-27 03:14:35 +02:00
f72253966b Throw more test cases at the message parser, fix edge case 2018-04-27 02:56:35 +02:00
b4bdcd4939 Update README 2018-04-26 21:37:58 +02:00
0648b67cb8 Use random session IDs instead of jwt 2018-04-26 21:32:21 +02:00
6f0ea05f4b Use shorter asset hashes 2018-04-26 21:19:47 +02:00
1b202e7c2b Make sure the cookie stored channel exists on the correct server 2018-04-26 20:25:41 +02:00
e132c8201f Use node 10.0.0 on travis 2018-04-26 19:57:39 +02:00
4f72e164d7 Use immer 2018-04-25 05:52:55 +02:00
7f755d2a83 Actually make sure the user is in the channel before embedding channel data 2018-04-24 21:21:42 +02:00
8724121552 Update redux to 4.0.0 2018-04-17 21:53:41 +02:00
0ebd2e5c38 Update client dependencies 2018-04-17 21:22:10 +02:00
0941ed8549 Add reset-config flag 2018-04-15 01:25:21 +02:00
39641c315f Add connect defaults readonly flag, closes #10 2018-04-15 01:02:28 +02:00
fcd204321a Fix css bundle name 2018-04-15 00:58:51 +02:00
d08bd43ba0 Hot reload server config 2018-04-15 00:57:11 +02:00
60190fbd98 Update prettier to 1.12 2018-04-13 20:58:45 +02:00
6ccc57ad64 Update gulp compress glob 2018-04-13 20:51:42 +02:00
94f3777f5f Handle css with webpack 2018-04-13 20:47:39 +02:00
3d4c1baeda Remove redundant eslint rules 2018-04-06 01:53:11 +02:00
b176b79144 Add prettier 2018-04-06 01:46:22 +02:00
0cbbc1b8ff Update client deps: react 16.3, babel 7 2018-04-05 21:16:37 +02:00
1ae7d867a9 Use node 8.10.0 on travis 2018-03-25 01:51:54 +01:00
87d7337d21 Update .travis.yml 2018-03-25 01:47:08 +01:00
19bcc51eb4 Update client dependencies 2018-03-25 01:34:41 +01:00
20c3855ced Add go 1.10 travis build 2018-02-19 00:01:48 +01:00
b9b6928111 Add go 1.9 travis build 2017-09-02 20:28:36 +02:00
d22758227d Add link metadata fetching package 2017-07-17 23:11:36 +02:00
a4a4588ae6 Add compareUsers test 2017-07-06 07:01:14 +02:00
8b44f68231 Move user sorting to a selector 2017-07-06 06:46:53 +02:00
c005fc7cae Add initial support for choosing to still connect when the server uses a self-signed cert and verify_vertificates is turned on 2017-07-04 11:28:56 +02:00
3f70567d56 Trim whitespace off IRC messages 2017-07-03 23:31:14 +02:00
8a62af5a73 Unvendor resync 2017-07-03 07:39:10 +02:00
0a96ebb428 Improve connection handling 2017-07-03 07:35:38 +02:00
9dffb541b9 Print ERROR messages 2017-07-03 07:25:38 +02:00
ae6ad0a5b9 Send nick_fail if the new nick is in use and the padded nick is the same as the old one 2017-07-03 01:07:55 +02:00
403f7d0942 Copy action payload before passing it to socket handlers 2017-07-03 00:52:16 +02:00
8a2fbaca7f Improve status tab error layout 2017-07-03 00:04:10 +02:00
18aff3ded6 Show last IRC connection error in status tab, log IRC connection errors 2017-07-02 03:31:00 +02:00
786d8013b9 Set InsecureSkipVerify correctly when theres no client cert, rename verify_client_certificates to verify_certificates 2017-06-30 07:20:38 +02:00
1903 changed files with 347465 additions and 106074 deletions

View File

@ -1,3 +1,5 @@
.git
dist
dispatch
client/dist
client/node_modules
client/node_modules
client/yarn-error.log

5
.gitignore vendored
View File

@ -1,6 +1,5 @@
build
release
dist
dispatch
client/dist
client/node_modules
client/yarn-error.log
ca-certificates.crt

45
.goreleaser.yml Normal file
View File

@ -0,0 +1,45 @@
builds:
- ldflags:
- -s -w -X github.com/khlieng/dispatch/version.Tag=v{{.Version}} -X github.com/khlieng/dispatch/version.Commit={{.ShortCommit}} -X github.com/khlieng/dispatch/version.Date={{.Date}}
env:
- CGO_ENABLED=0
goos:
- linux
- darwin
- windows
goarch:
- amd64
- arm
- arm64
goarm:
- 6
- 7
archives:
- files:
- none*
format_overrides:
- goos: windows
format: zip
replacements:
amd64: x64
darwin: mac
checksum:
name_template: "checksums.txt"
changelog:
filters:
exclude:
- "(?i)^update.*dep"
- Merge pull request
- Merge branch
release:
name_template: "{{.Version}}"

View File

@ -1,8 +1,7 @@
language: go
go:
- 1.8.3
- 1.9beta2
- 1.x
- tip
os:
@ -14,17 +13,25 @@ matrix:
- go: tip
install:
- go get github.com/jteeuwen/go-bindata/...
- GO111MODULE=off go get github.com/jteeuwen/go-bindata/...
- cd client
- nvm install 7.10.0
- nvm use 7.10.0
- nvm install 12.4.0
- nvm use 12.4.0
- npm install -g yarn
- npm install -g gulp
- yarn global add gulp
- yarn
script:
- npm run test:verbose
- yarn test:verbose
- gulp build
- cd ..
- go vet $(go list ./... | grep -v '/vendor/')
- go test -v -race $(go list ./... | grep -v '/vendor/')
- go vet ./...
- go test -v -race ./...
deploy:
- provider: script
skip_cleanup: true
script: git checkout -- . && curl -sL https://git.io/goreleaser | bash
on:
tags: true
condition: $TRAVIS_OS_NAME = linux && $TRAVIS_GO_VERSION = 1.*

View File

@ -1,7 +1,22 @@
FROM scratch
# Build
FROM golang:alpine AS build
ADD build/dispatch /
ADD ca-certificates.crt /etc/ssl/certs/
RUN apk add --update git make build-base && \
rm -rf /var/cache/apk/*
WORKDIR /go/src/github.com/khlieng/dispatch
COPY . /go/src/github.com/khlieng/dispatch
RUN chmod +x install.sh && ./install.sh
# Runtime
FROM alpine
RUN apk add --update ca-certificates && \
rm -rf /var/cache/apk/*
COPY --from=build /go/bin/dispatch /dispatch
EXPOSE 80/tcp
VOLUME ["/data"]

View File

@ -2,40 +2,46 @@
#### [Try it!](https://dispatch.khlieng.com)
![Dispatch](https://khlieng.com/dispatch.png)
![Dispatch](https://khlieng.com/dispatch.png?1)
### Features
* Searchable history
* Persistent connections
* Multiple servers and users
* Automatic HTTPS through Let's Encrypt
* Client certificates
- Searchable history
- Persistent connections
- Multiple servers and users
- Automatic HTTPS through Let's Encrypt
- Client certificates
## Usage
There is a few different ways of getting it:
### 1. Binary
- **[Windows (x64)](https://github.com/khlieng/dispatch/releases/download/v0.4/dispatch_windows_amd64.zip)**
- **[OS X (x64)](https://github.com/khlieng/dispatch/releases/download/v0.4/dispatch_darwin_amd64.zip)**
- **[Linux (x64)](https://github.com/khlieng/dispatch/releases/download/v0.4/dispatch_linux_amd64.tar.gz)**
- **[Windows (x64)](https://release.khlieng.com/khlieng/dispatch/windows_x64)**
- **[macOS (x64)](https://release.khlieng.com/khlieng/dispatch/mac_x64)**
- **[Linux (x64)](https://release.khlieng.com/khlieng/dispatch/linux_x64)**
- [Other versions](https://github.com/khlieng/dispatch/releases)
### 2. Go
This requires a [Go environment](http://golang.org/doc/install), version 1.8 or greater.
This requires a [Go environment](http://golang.org/doc/install), version 1.10 or greater.
Fetch, compile and run dispatch:
```bash
go get github.com/khlieng/dispatch
dispatch
```
To get some help run:
```bash
dispatch help
```
### 3. Docker
```bash
docker run -p <http port>:80 -p <https port>:443 -v <path>:/data khlieng/dispatch
```
@ -43,49 +49,66 @@ docker run -p <http port>:80 -p <https port>:443 -v <path>:/data khlieng/dispatc
## Build
### Server
```bash
cd $GOPATH/src/github.com/khlieng/dispatch
```bash
go install
```
### Client
This requires [Node.js](https://nodejs.org).
This requires [Node.js](https://nodejs.org) and [yarn](https://yarnpkg.com).
Fetch the dependencies:
```bash
npm install -g gulp
go get github.com/jteeuwen/go-bindata/...
cd $GOPATH/src/github.com/khlieng/dispatch/client
npm install
GO111MODULE=off go get github.com/jteeuwen/go-bindata/...
yarn global add gulp-cli
cd client
yarn
```
Run the build:
```bash
gulp build
```
The server needs to be rebuilt after this.
The server needs to be rebuilt to embed new client builds.
For development with hot reloading start the frontend:
For development with hot reloading enabled run:
```bash
gulp
```
And then the backend in a separate terminal:
```bash
dispatch --dev
```
## Libraries
The libraries this project is built with.
### Server
- [Bolt](https://github.com/boltdb/bolt)
- [Bolt](https://github.com/etcd-io/bbolt)
- [Bleve](https://github.com/blevesearch/bleve)
- [Cobra](https://github.com/spf13/cobra)
- [Viper](https://github.com/spf13/viper)
- [Lego](https://github.com/xenolf/lego)
- [CertMagic](https://github.com/mholt/certmagic)
### Client
- [React](https://github.com/facebook/react)
- [Redux](https://github.com/reactjs/redux)
- [Immutable](https://github.com/facebook/immutable-js)
- [React Virtualized](https://github.com/bvaughn/react-virtualized)
- [Immer](https://github.com/mweststrate/immer)
- [react-window](https://github.com/bvaughn/react-window)
- [Lodash](https://github.com/lodash/lodash)
## Big Thanks
Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][homepage]
[homepage]: https://saucelabs.com

File diff suppressed because one or more lines are too long

View File

@ -1,35 +0,0 @@
{
"presets": [
["es2015", { "modules": false, "loose": true }],
"react",
"stage-0"
],
"plugins": [
["module-resolver", {
"root": ["./src/js"],
"alias": {
"components": "./components",
"containers": "./containers",
"state": "./state",
"util": "./util"
}
}]
],
"env": {
"development": {
"plugins": ["react-hot-loader/babel"]
},
"test": {
"plugins": [
"rewire",
"transform-es2015-modules-commonjs"
]
},
"production": {
"plugins": [
"transform-react-inline-elements",
"transform-react-constant-elements"
]
}
}
}

View File

@ -1,29 +1,31 @@
{
"extends": "airbnb",
"extends": ["airbnb", "prettier", "prettier/react"],
"parser": "babel-eslint",
"env": {
"browser": true
},
"rules": {
"arrow-parens": 0,
"comma-dangle": [2, "never"],
"consistent-return": 0,
"jsx-a11y/click-events-have-key-events": 0,
"jsx-a11y/no-noninteractive-element-interactions": 0,
"jsx-a11y/no-static-element-interactions": 0,
"new-cap": [2, { "capIsNewExceptions": ["Map", "List", "Record", "Set"] }],
"no-console": 0,
"no-console": 1,
"no-param-reassign": 0,
"no-plusplus": 0,
"no-restricted-globals": 1,
"no-underscore-dangle": 1,
"react/destructuring-assignment": 0,
"react/jsx-filename-extension": 0,
"react/no-array-index-key": 0,
"react/jsx-props-no-spreading": 0,
"react/prop-types": 0,
"react/prefer-stateless-function": 0
},
"globals": {
"DEV": true
"react/state-in-constructor": 0,
"react/static-property-placement": 0
},
"settings": {
"import/resolver": {
"babel-module": {}
"webpack": {
"config": "webpack.config.prod.js"
}
}
}
}

5
client/.prettierrc.json Normal file
View File

@ -0,0 +1,5 @@
{
"singleQuote": true,
"trailingComma": "none",
"arrowParens": "avoid"
}

30
client/babel.config.js Normal file
View File

@ -0,0 +1,30 @@
module.exports = {
presets: [
[
'@babel/preset-env',
{
modules: false,
loose: true
}
],
'@babel/preset-react'
],
plugins: [
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-proposal-export-default-from',
'@babel/plugin-proposal-export-namespace-from',
'@babel/plugin-syntax-dynamic-import',
'react-hot-loader/babel'
],
env: {
test: {
plugins: ['@babel/plugin-transform-modules-commonjs']
},
production: {
plugins: [
'@babel/plugin-transform-react-inline-elements',
'@babel/plugin-transform-react-constant-elements'
]
}
}
};

35
client/css/fonts.css Normal file
View File

@ -0,0 +1,35 @@
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 400;
src: local('Montserrat-Regular'),
url(/font/Montserrat-Regular.woff2) format('woff2'),
url(/font/Montserrat-Regular.woff) format('woff');
}
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 700;
src: local('Montserrat-Bold'),
url(/font/Montserrat-Bold.woff2) format('woff2'),
url(/font/Montserrat-Bold.woff) format('woff');
}
@font-face {
font-family: 'Roboto Mono';
font-style: normal;
font-weight: 400;
src: local('Roboto Mono'), local('RobotoMono-Regular'),
url(/font/RobotoMono-Regular.woff2) format('woff2'),
url(/font/RobotoMono-Regular.woff) format('woff');
}
@font-face {
font-family: 'Roboto Mono';
font-style: normal;
font-weight: 700;
src: local('Roboto Mono Bold'), local('RobotoMono-Bold'),
url(/font/RobotoMono-Bold.woff2) format('woff2'),
url(/font/RobotoMono-Bold.woff) format('woff');
}

1132
client/css/style.css Normal file

File diff suppressed because it is too large Load Diff

View File

@ -4,115 +4,111 @@ var url = require('url');
var gulp = require('gulp');
var gutil = require('gulp-util');
var nano = require('gulp-cssnano');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var cache = require('gulp-cached');
var express = require('express');
var proxy = require('express-http-proxy');
var webpack = require('webpack');
var through = require('through2');
var br = require('brotli');
var del = require('del');
function brotli(opts) {
return through.obj(function(file, enc, callback) {
return through.obj(function (file, enc, callback) {
if (file.isNull()) {
return callback(null, file);
}
if (file.isStream()) {
this.emit('error', new gutil.PluginError('brotli', 'Streams not supported'));
this.emit(
'error',
new gutil.PluginError('brotli', 'Streams not supported')
);
} else if (file.isBuffer()) {
file.path += '.br';
file.contents = new Buffer(br.compress(file.contents, opts).buffer);
file.contents = Buffer.from(br.compress(file.contents, opts).buffer);
return callback(null, file);
}
});
}
gulp.task('css', function() {
return gulp.src(['src/css/fonts.css', 'src/css/fontello.css', 'src/css/style.css'])
.pipe(concat('bundle.css'))
.pipe(autoprefixer())
.pipe(nano())
.pipe(gulp.dest('dist'));
});
function clean() {
return del(['dist']);
}
gulp.task('js', function(cb) {
function js(cb) {
var config = require('./webpack.config.prod.js');
var compiler = webpack(config);
process.env['NODE_ENV'] = 'production';
compiler.run(function(err, stats) {
compiler.run(function (err, stats) {
if (err) throw new gutil.PluginError('webpack', err);
gutil.log('[webpack]', stats.toString({
colors: true
}));
gutil.log(
'[webpack]',
stats.toString({
colors: true
})
);
if (stats.hasErrors()) process.exit(1);
cb();
});
});
gulp.task('fonts', function() {
return gulp.src('src/font/*')
.pipe(gulp.dest('dist/font'));
});
gulp.task('fonts:woff', function() {
return gulp.src('src/font/*(*.woff|*.woff2)')
.pipe(gulp.dest('dist/br/font'));
});
gulp.task('config', function() {
return gulp.src('../config.default.toml')
.pipe(gulp.dest('dist/br'));
});
function compress() {
return gulp.src(['dist/**/!(*.br|*.woff|*.woff2)', '!dist/{br,br/**}'])
.pipe(brotli({ quality: 11 }))
.pipe(gulp.dest('dist/br'));
}
gulp.task('compress', ['css', 'js', 'fonts'], compress);
gulp.task('compress:dev', ['css', 'fonts'], compress);
function config() {
return gulp.src('../config.default.toml').pipe(gulp.dest('dist'));
}
gulp.task('bindata', ['compress', 'config'], function(cb) {
exec('go-bindata -nomemcopy -nocompress -pkg assets -o ../assets/bindata.go -prefix "dist/br" dist/br/...', cb);
});
function public() {
return gulp.src('public/**/*').pipe(gulp.dest('dist'));
}
gulp.task('bindata:dev', ['compress:dev', 'config'], function(cb) {
exec('go-bindata -debug -pkg assets -o ../assets/bindata.go -prefix "dist/br" dist/br/...', cb);
});
function compress() {
return gulp
.src(['dist/**/*(*.js|*.css|*.json)', '!dist/**/*(*.dev.js)'])
.pipe(brotli({ quality: 11 }))
.pipe(gulp.dest('dist'));
}
gulp.task('dev', ['css', 'fonts', 'fonts:woff', 'config', 'compress:dev', 'bindata:dev'], function() {
gulp.watch('src/css/*.css', ['css']);
function cleanup() {
return del(['dist/**/*(*.js|*.css|*.json|*.map)']);
}
function bindata(cb) {
exec(
'go-bindata -nomemcopy -nocompress -pkg assets -o ../assets/bindata.go -prefix "dist" dist/...',
cb
);
}
function serve() {
var config = require('./webpack.config.dev.js');
var compiler = webpack(config);
var app = express();
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
headers: {
'Access-Control-Allow-Origin': '*'
}
}));
app.use(
require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
headers: {
'Access-Control-Allow-Origin': '*'
}
})
);
app.use(require('webpack-hot-middleware')(compiler));
app.use('/', express.static('dist'));
app.use('*', proxy('localhost:1337', {
proxyReqPathResolver: function(req) {
return req.originalUrl;
}
}));
app.use(
'*',
proxy('localhost:1337', {
proxyReqPathResolver: function (req) {
return req.originalUrl;
}
})
);
app.listen(3000, function (err) {
if (err) {
@ -122,8 +118,20 @@ gulp.task('dev', ['css', 'fonts', 'fonts:woff', 'config', 'compress:dev', 'binda
console.log('Listening at http://localhost:3000');
});
});
}
gulp.task('build', ['css', 'js', 'fonts', 'fonts:woff', 'config', 'compress', 'bindata']);
const build = gulp.series(
clean,
gulp.parallel(js, config),
compress,
cleanup,
bindata
);
gulp.task('default', ['dev']);
const dev = gulp.series(
clean,
gulp.parallel(serve, public, gulp.series(config, bindata))
);
gulp.task('build', build);
gulp.task('default', dev);

11
client/js/boot.js Normal file
View File

@ -0,0 +1,11 @@
/* eslint-disable no-underscore-dangle */
window.__init__ = fetch('/init', {
credentials: 'same-origin'
}).then(res => {
if (res.ok) {
return res.json();
}
throw new Error(res.statusText);
});

View File

@ -1,10 +1,14 @@
import { COMMAND } from 'state/actions';
import { join, part, invite, kick, setTopic } from 'state/channels';
import { sendMessage, raw } from 'state/messages';
import { openPrivateChat } from 'state/privateChats';
import { setNick, disconnect, whois, away } from 'state/servers';
import { select } from 'state/tab';
import { find } from 'util';
import createCommandMiddleware, { beforeHandler, notFoundHandler } from './middleware/command';
import { find, isChannel } from 'utils';
import createCommandMiddleware, {
beforeHandler,
notFoundHandler
} from './middleware/command';
const help = [
'/join <channel> - Join a channel',
@ -26,7 +30,8 @@ const help = [
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);
const findHelp = cmd =>
find(help, line => line.slice(1, line.indexOf(' ')) === cmd);
export default createCommandMiddleware(COMMAND, {
join({ dispatch, server }, channel) {
@ -41,10 +46,10 @@ export default createCommandMiddleware(COMMAND, {
}
},
part({ dispatch, server, channel, isChannel }, partChannel) {
part({ dispatch, server, channel, inChannel }, partChannel) {
if (partChannel) {
dispatch(part([partChannel], server));
} else if (isChannel) {
} else if (inChannel) {
dispatch(part([channel], server));
} else {
return error('This is not a channel');
@ -75,13 +80,15 @@ export default createCommandMiddleware(COMMAND, {
topic({ dispatch, getState, server, channel }, ...newTopic) {
if (newTopic.length > 0) {
dispatch(setTopic(newTopic.join(' '), channel, server));
} else {
const topic = getState().channels.getIn([server, channel, 'topic']);
return;
}
if (channel) {
const { topic } = getState().channels[server][channel];
if (topic) {
return text(topic);
}
return 'No topic set';
}
return 'No topic set';
},
msg({ dispatch, server }, target, ...message) {
@ -92,6 +99,9 @@ export default createCommandMiddleware(COMMAND, {
const msg = message.join(' ');
if (msg !== '') {
dispatch(sendMessage(message.join(' '), target, server));
if (!isChannel(target)) {
dispatch(openPrivateChat(server, target));
}
dispatch(select(server, target));
} else {
return error('Messages can not be empty');
@ -111,8 +121,8 @@ export default createCommandMiddleware(COMMAND, {
}
},
invite({ dispatch, server, channel, isChannel }, user, inviteChannel) {
if (!inviteChannel && !isChannel) {
invite({ dispatch, server, channel, inChannel }, user, inviteChannel) {
if (!inviteChannel && !inChannel) {
return error('This is not a channel');
}
@ -125,8 +135,8 @@ export default createCommandMiddleware(COMMAND, {
}
},
kick({ dispatch, server, channel, isChannel }, user) {
if (!isChannel) {
kick({ dispatch, server, channel, inChannel }, user) {
if (!inChannel) {
return error('This is not a channel');
}
@ -160,10 +170,7 @@ export default createCommandMiddleware(COMMAND, {
dispatch(raw(cmd, server));
return prompt(`=> ${cmd}`);
}
return [
prompt('=> /raw'),
error('Missing message')
];
return [prompt('=> /raw'), error('Missing message')];
},
help(_, ...commands) {
@ -184,9 +191,6 @@ export default createCommandMiddleware(COMMAND, {
},
[notFoundHandler](ctx, command, ...params) {
if (command === command.toUpperCase()) {
return this.raw(ctx, command, ...params);
}
return error(`=> /${command}: No such command`);
return this.raw(ctx, command, ...params);
}
});

View File

@ -0,0 +1,93 @@
import React, { Suspense, lazy, useState, useEffect } from 'react';
import Route from 'containers/Route';
import AppInfo from 'components/AppInfo';
import TabList from 'components/TabList';
import cn from 'classnames';
const Modals = lazy(() => import('components/modals'));
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,
openModal,
newVersionAvailable,
hasOpenModals
}) => {
const [renderModals, setRenderModals] = useState(false);
if (!renderModals && hasOpenModals) {
setRenderModals(true);
}
const [starting, setStarting] = useState(true);
useEffect(() => {
setTimeout(() => setStarting(false), 1000);
}, []);
const mainClass = cn('main-container', {
'off-canvas': showTabList
});
const handleClick = () => {
if (showTabList) {
hideMenu();
}
};
return (
<div className="wrap" onClick={handleClick}>
{!starting && !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}
openModal={openModal}
/>
<div className={mainClass}>
<Suspense fallback={<div className="suspense-fallback">...</div>}>
<Route name="chat">
<Chat />
</Route>
<Route name="connect">
<Connect />
</Route>
<Route name="settings">
<Settings />
</Route>
</Suspense>
<Suspense
fallback={<div className="suspense-modal-fallback">...</div>}
>
{renderModals && <Modals />}
</Suspense>
</div>
</div>
</div>
);
};
export default App;

View 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;

View File

@ -1,5 +1,6 @@
import React from 'react';
import { Provider } from 'react-redux';
import { hot } from 'react-hot-loader';
import App from 'containers/App';
const Root = ({ store }) => (
@ -8,4 +9,4 @@ const Root = ({ store }) => (
</Provider>
);
export default Root;
export default hot(module)(Root);

View File

@ -0,0 +1,124 @@
import React, { PureComponent } from 'react';
import classnames from 'classnames';
import get from 'lodash/get';
import { FiPlus, FiUser, FiSettings } from 'react-icons/fi';
import Button from 'components/ui/Button';
import TabListItem from 'containers/TabListItem';
import { count } from 'utils';
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,
openModal
} = 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}
/>
);
const chanCount = count(server.channels, c => c.joined);
const chanLimit =
get(srv.features, ['CHANLIMIT', '#'], 0) || srv.features.MAXCHANNELS;
let chanLabel;
if (chanLimit > 0) {
chanLabel = (
<span>
<span className="success">{chanCount}</span>/{chanLimit}
</span>
);
} else if (chanCount > 0) {
chanLabel = <span className="success">{chanCount}</span>;
}
tabs.push(
<div
key={`${address}-chans}`}
className="tab-label"
onClick={() => openModal('channel', address)}
>
<span>CHANNELS {chanLabel}</span>
<Button title="Join Channel">+</Button>
</div>
);
server.channels.forEach(({ name, joined }) =>
tabs.push(
<TabListItem
key={address + name}
server={address}
target={name}
content={name}
joined={joined}
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">
<span>
DIRECT MESSAGES{' '}
<span style={{ color: '#6bb758' }}>
{privateChats[address].length}
</span>
</span>
{/* <Button>+</Button> */}
</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 icon={FiPlus} onClick={this.handleConnectClick} />
<Button icon={FiUser} />
<Button icon={FiSettings} onClick={this.handleSettingsClick} />
</div>
</div>
);
}
}

View File

@ -0,0 +1,29 @@
import React from 'react';
import classnames from 'classnames';
const TabListItem = ({
target,
content,
server,
selected,
connected,
joined,
error,
onClick
}) => {
const className = classnames({
'tab-server': !target,
success: !target && connected,
error: (!target && !connected) || (!joined && error),
disabled: !!target && !error && joined === false,
selected
});
return (
<p className={className} onClick={() => onClick(server, target)}>
<span className="tab-content">{content}</span>
</p>
);
};
export default TabListItem;

View File

@ -0,0 +1,153 @@
import React, { memo, useState, useEffect, useRef } from 'react';
import Modal from 'react-modal';
import { useSelector, useDispatch } from 'react-redux';
import { FiUsers, FiX } from 'react-icons/fi';
import useModal from 'components/modals/useModal';
import Button from 'components/ui/Button';
import { join } from 'state/channels';
import { select } from 'state/tab';
import { searchChannels } from 'state/channelSearch';
import { linkify } from 'utils';
const Channel = memo(({ server, name, topic, userCount, joined }) => {
const dispatch = useDispatch();
const handleClick = () => dispatch(join([name], server));
return (
<div className="modal-channel-result">
<div className="modal-channel-result-header">
<h2 className="modal-channel-name" onClick={handleClick}>
{name}
</h2>
<FiUsers />
<span className="modal-channel-users">{userCount}</span>
{joined ? (
<span style={{ color: '#6bb758' }}>Joined</span>
) : (
<Button
className="modal-channel-button-join"
category="normal"
onClick={handleClick}
>
Join
</Button>
)}
</div>
<p className="modal-channel-topic">{linkify(topic)}</p>
</div>
);
});
const AddChannel = () => {
const [modal, server, closeModal] = useModal('channel');
const channels = useSelector(state => state.channels);
const search = useSelector(state => state.channelSearch);
const dispatch = useDispatch();
const [q, setQ] = useState('');
const inputEl = useRef();
const resultsEl = useRef();
const prevSearch = useRef('');
useEffect(() => {
if (modal.isOpen) {
dispatch(searchChannels(server, ''));
setTimeout(() => inputEl.current.focus(), 0);
} else {
prevSearch.current = '';
setQ('');
}
}, [modal.isOpen]);
const handleSearch = e => {
let nextQ = e.target.value.trim().toLowerCase();
setQ(nextQ);
if (nextQ !== q) {
resultsEl.current.scrollTop = 0;
while (nextQ.charAt(0) === '#') {
nextQ = nextQ.slice(1);
}
if (nextQ !== prevSearch.current) {
prevSearch.current = nextQ;
dispatch(searchChannels(server, nextQ));
}
}
};
const handleKey = e => {
if (e.key === 'Enter') {
let channel = e.target.value.trim();
if (channel !== '') {
closeModal(false);
if (channel.charAt(0) !== '#') {
channel = `#${channel}`;
}
dispatch(join([channel], server));
dispatch(select(server, channel));
}
}
};
const handleLoadMore = () =>
dispatch(searchChannels(server, q, search.results.length));
let hasMore = !search.end;
if (hasMore) {
if (search.results.length < 10) {
hasMore = false;
} else if (
search.results.length > 10 &&
(search.results.length - 10) % 50 !== 0
) {
hasMore = false;
}
}
return (
<Modal {...modal}>
<div className="modal-channel-input-wrap">
<input
ref={inputEl}
type="text"
value={q}
placeholder="Enter channel name"
onKeyDown={handleKey}
onChange={handleSearch}
/>
<Button
icon={FiX}
className="modal-close modal-channel-close"
onClick={closeModal}
/>
</div>
<div ref={resultsEl} className="modal-channel-results">
{search.results.map(channel => (
<Channel
key={`${server} ${channel.name}`}
server={server}
joined={channels[server]?.[channel.name]?.joined}
{...channel}
/>
))}
{hasMore && (
<Button
className="modal-channel-button-more"
onClick={handleLoadMore}
>
Load more
</Button>
)}
</div>
</Modal>
);
};
export default AddChannel;

View File

@ -0,0 +1,26 @@
import React from 'react';
import Modal from 'react-modal';
import useModal from 'components/modals/useModal';
import Button from 'components/ui/Button';
const Confirm = () => {
const [modal, payload, closeModal] = useModal('confirm');
const { question, confirmation, onConfirm } = payload;
const handleConfirm = () => {
closeModal(false);
onConfirm();
};
return (
<Modal {...modal}>
<p>{question}</p>
<Button onClick={handleConfirm}>{confirmation || 'OK'}</Button>
<Button category="normal" onClick={closeModal}>
Cancel
</Button>
</Modal>
);
};
export default Confirm;

View File

@ -0,0 +1,26 @@
import React from 'react';
import Modal from 'react-modal';
import { useSelector } from 'react-redux';
import { FiX } from 'react-icons/fi';
import Button from 'components/ui/Button';
import useModal from 'components/modals/useModal';
import { getSelectedChannel } from 'state/channels';
import { linkify } from 'utils';
const Topic = () => {
const [modal, channel, closeModal] = useModal('topic');
const topic = useSelector(state => getSelectedChannel(state)?.topic);
return (
<Modal {...modal}>
<div className="modal-header">
<h2>Topic in {channel}</h2>
<Button icon={FiX} className="modal-close" onClick={closeModal} />
</div>
<p className="modal-content">{linkify(topic)}</p>
</Modal>
);
};
export default Topic;

View File

@ -0,0 +1,14 @@
import React, { memo } from 'react';
import AddChannel from 'components/modals/AddChannel';
import Confirm from 'components/modals/Confirm';
import Topic from 'components/modals/Topic';
const Modals = () => (
<>
<AddChannel />
<Confirm />
<Topic />
</>
);
export default memo(Modals, () => true);

View File

@ -0,0 +1,46 @@
import { useCallback } from 'react';
import Modal from 'react-modal';
import { useSelector, useDispatch } from 'react-redux';
import { closeModal } from 'state/modals';
Modal.setAppElement('#root');
const defaultPayload = {};
export default function useModal(name) {
const isOpen = useSelector(state => state.modals[name]?.isOpen || false);
const payload = useSelector(
state => state.modals[name]?.payload || defaultPayload
);
const dispatch = useDispatch();
const handleRequestClose = useCallback(
(dismissed = true) => {
dispatch(closeModal(name));
if (dismissed && payload.onDismiss) {
payload.onDismiss();
}
},
[payload.onDismiss]
);
const modalProps = {
isOpen,
contentLabel: name,
onRequestClose: handleRequestClose,
className: {
base: `modal modal-${name}`,
afterOpen: 'modal-opening',
beforeClose: 'modal-closing'
},
overlayClassName: {
base: 'modal-overlay',
afterOpen: 'modal-overlay-opening',
beforeClose: 'modal-overlay-closing'
},
closeTimeoutMS: 200
};
return [modalProps, payload, handleRequestClose];
}

View File

@ -1,4 +1,5 @@
import React, { Component } from 'react';
import { isChannel } from 'utils';
import ChatTitle from './ChatTitle';
import Search from './Search';
import MessageBox from './MessageBox';
@ -9,7 +10,7 @@ export default class Chat extends Component {
handleCloseClick = () => {
const { tab, part, closePrivateChat, disconnect } = this.props;
if (tab.isChannel()) {
if (isChannel(tab)) {
part([tab.name], tab.server);
} else if (tab.name) {
closePrivateChat(tab.server, tab.name);
@ -20,7 +21,7 @@ export default class Chat extends Component {
handleSearch = phrase => {
const { tab, searchMessages } = this.props;
if (tab.isChannel()) {
if (isChannel(tab)) {
searchMessages(tab.server, tab.name, phrase);
}
};
@ -49,12 +50,14 @@ export default class Chat extends Component {
render() {
const {
channel,
coloredNicks,
currentInputHistoryEntry,
hasMoreMessages,
messages,
nick,
search,
showUserList,
status,
tab,
title,
users,
@ -62,14 +65,14 @@ export default class Chat extends Component {
addFetchedMessages,
fetchMessages,
inputActions,
openModal,
runCommand,
sendMessage,
toggleSearch,
toggleUserList
} = this.props;
let chatClass;
if (tab.isChannel()) {
if (isChannel(tab)) {
chatClass = 'chat-channel';
} else if (tab.name) {
chatClass = 'chat-private';
@ -81,21 +84,22 @@ export default class Chat extends Component {
<div className={chatClass}>
<ChatTitle
channel={channel}
status={status}
tab={tab}
title={title}
openModal={openModal}
onCloseClick={this.handleCloseClick}
onTitleChange={this.handleTitleChange}
onToggleSearch={toggleSearch}
onToggleUserList={toggleUserList}
/>
<Search
search={search}
onSearch={this.handleSearch}
/>
<Search search={search} onSearch={this.handleSearch} />
<MessageBox
coloredNicks={coloredNicks}
hasMoreMessages={hasMoreMessages}
messages={messages}
tab={tab}
hideTopDate={search.show}
onAddMore={addFetchedMessages}
onFetchMore={fetchMessages}
onNickClick={this.handleNickClick}
@ -111,6 +115,7 @@ export default class Chat extends Component {
{...inputActions}
/>
<UserList
coloredNicks={coloredNicks}
showUserList={showUserList}
users={users}
onNickClick={this.handleNickClick}

View File

@ -0,0 +1,78 @@
import React, { memo } from 'react';
import { FiUsers, FiSearch, FiX } from 'react-icons/fi';
import Navicon from 'components/ui/Navicon';
import Button from 'components/ui/Button';
import Editable from 'components/ui/Editable';
import { isValidServerName } from 'state/servers';
import { isChannel } from 'utils';
const ChatTitle = ({
status,
title,
tab,
channel,
openModal,
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">
{channel && channel.topic && (
<span
className="chat-topic"
onClick={() => openModal('topic', channel.name)}
>
{channel.topic}
</span>
)}
{serverError}
</div>
{tab.name && (
<Button icon={FiSearch} title="Search" onClick={onToggleSearch} />
)}
<Button icon={FiX} title={closeTitle} onClick={onCloseClick} />
<Button
icon={FiUsers}
className="button-userlist"
onClick={onToggleUserList}
/>
</div>
<div className="userlist-bar">
<FiUsers />
{channel && channel.users.length}
</div>
</div>
);
};
export default memo(ChatTitle);

View File

@ -0,0 +1,47 @@
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
});
if (message.type === 'date') {
return (
<div className={className} style={style}>
{message.content}
<hr />
</div>
);
}
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);

View File

@ -0,0 +1,305 @@
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 { formatDate, measureScrollBarWidth } from 'utils';
import { getScrollPos, saveScrollPos } from 'utils/scrollPosition';
import { windowHeight } from 'utils/size';
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 = 150;
const scrollBarWidth = `${measureScrollBarWidth()}px`;
const hasSameLastMessage = (m1, m2) => {
if (m1.length === 0 || m2.length === 0) {
if (m1.length === 0 && m2.length === 0) {
return true;
}
return false;
}
return m1[m1.length - 1].id === m2[m2.length - 1].id;
};
export default class MessageBox extends PureComponent {
state = { topDate: '' };
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();
}
componentDidUpdate(prevProps) {
const { messages } = this.props;
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 &&
!hasSameLastMessage(messages, prevProps.messages)
) {
this.list.current.scrollToItem(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 && prevProps.messages.length > 0) {
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;
}
if (index === messages.length + 1) {
return 7;
}
return messages[index - 1].height;
};
getItemKey = index => {
const { messages } = this.props;
if (index === 0) {
return 'top';
}
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());
const { messages } = this.props;
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(messages.length + 1);
} else if (messages.length > 0) {
let totalHeight = 14;
for (let i = 0; i < messages.length; i++) {
totalHeight += messages[i].height;
}
const messageBoxHeight = windowHeight() - 100;
if (totalHeight > messageBoxHeight) {
this.initialScrollTop = totalHeight;
}
}
}
};
saveScrollPos = () => {
if (this.bottom) {
saveScrollPos(this.scrollKey, -1);
} else {
saveScrollPos(this.scrollKey, this.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.scrollTop = scrollOffset;
this.bottom = scrollOffset + clientHeight >= scrollHeight - 20;
};
handleItemsRendered = ({ visibleStartIndex }) => {
const startIndex = visibleStartIndex === 0 ? 0 : visibleStartIndex - 1;
const firstVisibleMessage = this.props.messages[startIndex];
if (firstVisibleMessage && firstVisibleMessage.date) {
this.setState({ topDate: formatDate(firstVisibleMessage.date) });
} else {
this.setState({ topDate: '' });
}
};
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;
}
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() {
const { messages, hideTopDate } = this.props;
const { topDate } = this.state;
const dateContainerStyle = {
right: scrollBarWidth
};
return (
<div
className="messagebox"
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}
>
<div
className="messagebox-topdate-container"
style={dateContainerStyle}
>
{!hideTopDate && topDate && (
<span className="messagebox-topdate">{topDate}</span>
)}
</div>
<AutoSizer>
{({ width, height }) => (
<List
ref={this.list}
outerRef={this.outer}
width={width}
height={height}
itemCount={messages.length + 2}
itemKey={this.getItemKey}
itemSize={this.getRowHeight}
estimatedItemSize={32}
initialScrollOffset={this.initialScrollTop}
onScroll={this.handleScroll}
onItemsRendered={this.handleItemsRendered}
className="messagebox-window"
overscanCount={5}
>
{this.renderMessage}
</List>
)}
</AutoSizer>
</div>
);
}
}

View 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);

View File

@ -0,0 +1,39 @@
import React, { memo, useRef, useEffect } from 'react';
import { FiSearch } from 'react-icons/fi';
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">
<FiSearch className="search-input-icon" />
<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);

View 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);

View File

@ -0,0 +1,95 @@
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;
}
if (index === users.length + 1) {
return 10;
}
return 24;
};
getItemKey = index => {
const { users } = this.props;
if (index === 0) {
return 'top';
}
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}
overscanCount={5}
>
{this.renderUser}
</List>
)}
</AutoSizer>
</div>
);
}
}

View 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);

View File

@ -0,0 +1,214 @@
import React, { Component } from 'react';
import { createSelector } from 'reselect';
import { Form, withFormik } from 'formik';
import Navicon from 'components/ui/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';
import { FiMoreHorizontal } from 'react-icons/fi';
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" noTrim />
<TextInput name="realname" noTrim />
</div>
);
};
transformPort = port => {
if (!port) {
return this.props.values.tls ? 6697 : 6667;
}
return port;
};
transformChannels = channels => {
const comma = channels[channels.length - 1] === ',';
channels = channels
.split(',')
.map(channel => {
channel = channel.trim();
if (channel) {
if (isValidChannel(channel, false) && channel[0] !== '#') {
channel = `#${channel}`;
}
}
return channel;
})
.filter(s => s)
.join(',');
return comma ? `${channels},` : channels;
};
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" noTrim />
<div className="connect-form-address">
<TextInput name="host" noError />
<TextInput
name="port"
type="number"
blurTransform={this.transformPort}
noError
/>
<Checkbox
name="tls"
label="SSL"
topLabel
onChange={this.handleSSLChange}
/>
</div>
<Error name="host" />
<Error name="port" />
<TextInput name="nick" />
<TextInput name="channels" transform={this.transformChannels} />
{this.state.showOptionals && this.renderOptionals()}
<Button
className="connect-form-button-optionals"
icon={FiMoreHorizontal}
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 || false
};
},
validate: values => {
const errors = {};
if (!values.host) {
errors.host = 'Host is required';
} else if (values.host.indexOf('.') < 1) {
errors.host = 'Invalid host';
}
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';
}
const channels = values.channels.split(',');
for (let i = channels.length - 1; i >= 0; i--) {
if (i === channels.length - 1 && channels[i] === '') {
/* eslint-disable-next-line no-continue */
continue;
}
if (!isValidChannel(channels[i])) {
errors.channels = 'Invalid channel(s)';
break;
}
}
return errors;
},
handleSubmit: (values, { props }) => {
const { connect, select, join } = props;
const channels = values.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);

View File

@ -0,0 +1,87 @@
import React, { useCallback } from 'react';
import Navicon from 'components/ui/Navicon';
import Button from 'components/ui/Button';
import Checkbox from 'components/ui/Checkbox';
import FileInput from 'components/ui/FileInput';
const Settings = ({
settings,
installable,
version,
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="settings-button 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>
{version && (
<div className="settings-version">
<p>{version.tag}</p>
<p>Commit: {version.commit}</p>
<p>Build Date: {version.date}</p>
</div>
)}
</div>
</div>
);
};
export default Settings;

View File

@ -0,0 +1,21 @@
import React from 'react';
import cn from 'classnames';
const Button = ({ children, category, className, icon: Icon, ...props }) => (
<button
className={cn(
{
[`button-${category}`]: category,
'icon-button': Icon && !children
},
className
)}
type="button"
{...props}
>
{Icon && <Icon />}
{children}
</button>
);
export default Button;

View 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;

View File

@ -0,0 +1,111 @@
import React, { PureComponent, createRef } from 'react';
import cn from 'classnames';
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();
} else 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, editable, value } = this.props;
const style = {
width: this.state.width,
textIndent: this.state.indent,
paddingLeft: 0
};
return this.state.editing ? (
<input
ref={this.inputEl}
className={`editable-wrap ${className}`}
type="text"
value={value}
onBlur={this.handleBlur}
onChange={this.handleChange}
onKeyDown={this.handleKey}
onFocus={this.handleFocus}
style={style}
spellCheck={false}
/>
) : (
<div
className={cn('editable-wrap', {
'editable-wrap-editable': editable
})}
onClick={this.startEditing}
>
{children}
</div>
);
}
}

View 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>
);
}
}

View File

@ -0,0 +1,19 @@
import React from 'react';
import { FiMenu } from 'react-icons/fi';
import { useDispatch } from 'react-redux';
import Button from 'components/ui/Button';
import { toggleMenu } from 'state/ui';
const Navicon = () => {
const dispatch = useDispatch();
return (
<Button
className="navicon"
icon={FiMenu}
onClick={() => dispatch(toggleMenu())}
/>
);
};
export default Navicon;

View File

@ -0,0 +1,139 @@
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';
const getValue = (e, trim) => {
let v = e.target.value;
if (trim) {
v = v.trim();
}
if (e.target.type === 'number') {
v = parseFloat(v);
/* eslint-disable-next-line no-self-compare */
if (v !== v) {
v = '';
}
}
return v;
};
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,
noTrim,
transform,
blurTransform,
...props
} = this.props;
return (
<FastField
name={name}
render={({ field, form }) => (
<>
<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}
onChange={e => {
let v = getValue(e, !noTrim);
if (transform) {
v = transform(v);
}
if (v !== field.value) {
form.setFieldValue(name, v);
if (props.onChange) {
props.onChange(e);
}
}
}}
onBlur={e => {
if (blurTransform) {
const v = blurTransform(getValue(e));
if (v && v !== field.value) {
form.setFieldValue(name, v, false);
}
}
field.onBlur(e);
if (props.onBlur) {
props.onBlur(e);
}
}}
/>
<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} />}
</>
)}
/>
);
}
}

View File

@ -0,0 +1,24 @@
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 }) => (
<Checkbox
name={name}
checked={field.value}
onChange={e => {
field.onChange(e);
if (onChange) {
onChange(e);
}
}}
{...props}
/>
)}
/>
);
export default memo(FormikCheckbox);

View 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;

View File

@ -1,23 +1,26 @@
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import App from 'components/App';
import { getConnected } from 'state/app';
import { getSortedChannels } from 'state/channels';
import { getSortedPrivateChats } from 'state/privateChats';
import { openModal, getHasOpenModals } from 'state/modals';
import { getPrivateChats } from 'state/privateChats';
import { getServers } from 'state/servers';
import { getSelectedTab, select } from 'state/tab';
import { getShowTabList, hideMenu } from 'state/ui';
import { push } from 'util/router';
import connect from 'utils/connect';
import { push } from 'utils/router';
const mapState = createStructuredSelector({
channels: getSortedChannels,
connected: getConnected,
privateChats: getSortedPrivateChats,
privateChats: getPrivateChats,
servers: getServers,
showTabList: getShowTabList,
tab: getSelectedTab
tab: getSelectedTab,
newVersionAvailable: state => state.app.newVersionAvailable,
hasOpenModals: getHasOpenModals
});
const mapDispatch = { push, select, hideMenu };
const mapDispatch = { push, select, hideMenu, openModal };
export default connect(mapState, mapDispatch)(App);

View File

@ -0,0 +1,88 @@
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 { openModal } from 'state/modals';
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,
openModal,
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);

View File

@ -1,13 +1,14 @@
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import Connect from 'components/pages/Connect';
import { getConnectDefaults } from 'state/app';
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
defaults: getConnectDefaults,
hexIP: state => getApp(state).hexIP
});
const mapDispatch = {

View File

@ -1,5 +1,5 @@
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import connect from 'utils/connect';
const Route = ({ route, name, children }) => {
if (route === name) {

View File

@ -0,0 +1,27 @@
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,
version: state => state.app.version
});
const mapDispatch = {
onCertChange: setCert,
onKeyChange: setKey,
uploadCert,
setSetting,
onInstall: () => appSet('installable', null)
};
export default connect(mapState, mapDispatch)(Settings);

View File

@ -0,0 +1,17 @@
import { createStructuredSelector } from 'reselect';
import get from 'lodash/get';
import TabListItem from 'components/TabListItem';
import connect from 'utils/connect';
const mapState = createStructuredSelector({
error: (state, { server, target }) => {
const messages = get(state, ['messages', server, target]);
if (messages && messages.length > 0) {
return messages[messages.length - 1].type === 'error';
}
return false;
}
});
export default connect(mapState)(TabListItem);

8
client/js/hot.js Normal file
View File

@ -0,0 +1,8 @@
import { setConfig } from 'react-hot-loader';
import ReactDOM from 'react-dom';
setConfig({
ignoreSFC: !!ReactDOM.setHotElementComparator,
pureSFC: true,
pureRender: true
});

35
client/js/index.js Normal file
View File

@ -0,0 +1,35 @@
import './hot';
import React from 'react';
import { render } 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/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 });
render(<Root store={store} />, document.getElementById('root'));
window.addEventListener('beforeinstallprompt', e => {
e.preventDefault();
store.dispatch(appSet('installable', e));
});
register({
onUpdate: () => store.dispatch(appSet('newVersionAvailable', true))
});

View File

@ -1,11 +1,11 @@
import { addMessages, inform, print } from 'state/messages';
import { isChannel } from 'util';
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) };
return { dispatch, getState, server, channel, inChannel: isChannel(channel) };
}
// TODO: Pull this out as convenience action
@ -27,7 +27,7 @@ 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 command = words[0].toLowerCase();
const params = words.slice(1);
if (command in handlers) {

View File

@ -1,7 +1,7 @@
import debounce from 'lodash/debounce';
const debounceKey = action => {
const key = action.socket.debounce.key;
const { key } = action.socket.debounce;
if (key) {
return `${action.type} ${key}`;
}

View File

@ -1,23 +1,27 @@
import capitalize from 'lodash/capitalize';
import { getRouter } from 'state';
import { getCurrentServerName } from 'state/servers';
import { observe } from 'util/observe';
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;
const { server, name } = router.params;
if (name) {
title = `${name} @ ${serverName}`;
title = `${name} @ ${serverName || server}`;
} else {
title = serverName;
title = serverName || server;
}
} else {
title = capitalize(router.route);
}
document.title = `${title} | Dispatch`;
if (title) {
document.title = `${title} | Dispatch`;
} else {
document.title = 'Dispatch';
}
});
}

View File

@ -1,9 +1,9 @@
import FontFaceObserver from 'fontfaceobserver';
import { setCharWidth } from 'state/app';
import { stringWidth } from 'util';
import { stringWidth } from 'utils';
export default function fonts({ store }) {
let charWidth = localStorage.charWidth;
let { charWidth } = localStorage;
if (charWidth) {
store.dispatch(setCharWidth(parseFloat(charWidth)));
}

View File

@ -1,6 +1,7 @@
import documentTitle from './documentTitle';
import fonts from './fonts';
import initialState from './initialState';
import route from './route';
import socket from './socket';
import storage from './storage';
import widthUpdates from './widthUpdates';
@ -8,6 +9,7 @@ import widthUpdates from './widthUpdates';
export default function runModules(ctx) {
fonts(ctx);
initialState(ctx);
route(ctx);
documentTitle(ctx);
socket(ctx);

View File

@ -0,0 +1,70 @@
import { socket as socketActions } from 'state/actions';
import { getConnected, getWrapWidth, appSet } from 'state/app';
import { searchChannels } from 'state/channelSearch';
import { addMessages } from 'state/messages';
import { setSettings } from 'state/settings';
import { when } from 'utils/observe';
function loadState({ store }, env) {
store.dispatch(setSettings(env.settings, true));
if (env.servers) {
store.dispatch({
type: socketActions.SERVERS,
data: env.servers
});
when(store, getConnected, () =>
// Cache top channels for each server
env.servers.forEach(({ host }) =>
store.dispatch(searchChannels(host, ''))
)
);
}
if (env.channels) {
store.dispatch({
type: socketActions.CHANNELS,
data: env.channels
});
}
if (env.openDMs) {
store.dispatch({
type: 'PRIVATE_CHATS',
privateChats: env.openDMs
});
}
if (env.users) {
store.dispatch({
type: socketActions.USERS,
...env.users
});
}
store.dispatch(
appSet({
connectDefaults: env.defaults,
initialized: true,
hexIP: env.hexIP,
version: env.version
})
);
if (env.messages) {
// Wait until wrapWidth gets initialized so that height calculations
// only happen once for these messages
when(store, getWrapWidth, () => {
const { messages, server, to, next } = env.messages;
store.dispatch(addMessages(messages, server, to, false, next));
});
}
}
/* eslint-disable no-underscore-dangle */
export default async function initialState(ctx) {
const env = await window.__init__;
ctx.socket.connect();
loadState(ctx, env);
}

View File

@ -0,0 +1,22 @@
import { updateSelection } from 'state/tab';
import { observe, when } from 'utils/observe';
export default function route({ store }) {
let first = true;
when(
store,
state => state.app.initialized,
() =>
observe(
store,
state => state.router,
router => {
if (!router.route || router.route === 'chat') {
store.dispatch(updateSelection(first));
first = false;
}
}
)
);
}

174
client/js/modules/socket.js Normal file
View File

@ -0,0 +1,174 @@
import { socketAction } from 'state/actions';
import { setConnected } from 'state/app';
import {
broadcast,
inform,
print,
addMessage,
addMessages
} from 'state/messages';
import { openModal } from 'state/modals';
import { reconnect } from 'state/servers';
import { select } from 'state/tab';
import { find } 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 }) {
dispatch(inform(`${user} joined the channel`, server, channels[0]));
},
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 }) {
if (oldNick) {
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));
},
error({ server, target, message }) {
dispatch(addMessage({ content: message, type: 'error' }, server, target));
},
connection_update({ server, errorType }) {
if (errorType === 'verify') {
dispatch(
openModal('confirm', {
question:
'The server is using a self-signed certificate, continue anyway?',
onConfirm: () =>
dispatch(
reconnect(server, {
skipVerify: true
})
)
})
);
}
},
_connected(connected) {
dispatch(setConnected(connected));
}
};
const afterHandlers = {
channel_forward(forward) {
const { selected } = getState().tab;
if (selected.server === forward.server && selected.name === forward.old) {
dispatch(select(forward.server, forward.new, true));
}
}
};
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);
if (type in afterHandlers) {
afterHandlers[type](data);
}
});
}

View File

@ -1,15 +1,17 @@
import Cookie from 'js-cookie';
import debounce from 'lodash/debounce';
import { getSelectedTab } from 'state/tab';
import { observe } from 'util/observe';
import { stringifyTab } from 'utils';
import { observe } from 'utils/observe';
const saveTab = debounce(tab =>
Cookie.set('tab', tab.toString(), { expires: 30 })
, 1000);
const saveTab = debounce(
tab => Cookie.set('tab', stringifyTab(tab), { expires: 30 }),
1000
);
export default function storage({ store }) {
observe(store, getSelectedTab, tab => {
if (tab.isChannel() || (tab.server && !tab.name)) {
if (tab.server) {
saveTab(tab);
}
});

View File

@ -1,7 +1,8 @@
import { getCharWidth } from 'state/app';
import { updateMessageHeight } from 'state/messages';
import { when } from 'util/observe';
import { measureScrollBarWidth } from 'util';
import { when } from 'utils/observe';
import { measureScrollBarWidth } from 'utils';
import { addResizeListener } from 'utils/size';
const menuWidth = 200;
const messagePadding = 30;
@ -13,8 +14,7 @@ export default function widthUpdates({ store }) {
const scrollBarWidth = measureScrollBarWidth();
let prevWrapWidth;
function updateWidth() {
const windowWidth = window.innerWidth;
function updateWidth(windowWidth) {
let wrapWidth = windowWidth - scrollBarWidth - messagePadding;
if (windowWidth > smallScreen) {
wrapWidth -= menuWidth;
@ -26,16 +26,6 @@ export default function widthUpdates({ store }) {
}
}
let resizeRAF;
function resize() {
if (resizeRAF) {
window.cancelAnimationFrame(resizeRAF);
}
resizeRAF = window.requestAnimationFrame(updateWidth);
}
updateWidth();
window.addEventListener('resize', resize);
addResizeListener(updateWidth, true);
});
}

View File

@ -0,0 +1,88 @@
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();
});
}
}

View File

@ -1,4 +1,4 @@
import { setServerName } from '../servers';
import { connect, setServerName } from '../servers';
describe('setServerName()', () => {
it('passes valid names to the server', () => {

View File

@ -1,18 +1,19 @@
import Immutable from 'immutable';
import reducer from '../channels';
import { connect } from '../servers';
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 = Immutable.fromJS({
let state = {
srv1: {
chan1: {}, chan2: {}, chan3: {}
chan1: {},
chan2: {},
chan3: {}
},
srv2: {
chan1: {}
}
});
};
state = reducer(state, {
type: actions.PART,
@ -20,7 +21,7 @@ describe('channel reducer', () => {
channels: ['chan1', 'chan3']
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
srv1: {
chan2: {}
},
@ -42,17 +43,17 @@ describe('channel reducer', () => {
user: 'nick2'
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
srv: {
chan1: {
users: [
{ mode: '', nick: 'nick1', renderName: 'nick1' },
]
name: 'chan1',
joined: true,
users: [{ mode: '', nick: 'nick1', renderName: 'nick1' }]
},
chan2: {
users: [
{ mode: '', nick: 'nick2', renderName: 'nick2' }
]
name: 'chan2',
joined: true,
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
}
}
});
@ -61,12 +62,12 @@ describe('channel reducer', () => {
it('handles SOCKET_JOIN', () => {
const state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
expect(state.toJS()).toEqual({
expect(state).toEqual({
srv: {
chan1: {
users: [
{ mode: '', nick: 'nick1', renderName: 'nick1' }
]
name: 'chan1',
joined: true,
users: [{ mode: '', nick: 'nick1', renderName: 'nick1' }]
}
}
});
@ -83,14 +84,16 @@ describe('channel reducer', () => {
user: 'nick2'
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
srv: {
chan1: {
users: [
{ mode: '', nick: 'nick1', renderName: 'nick1' }
]
name: 'chan1',
joined: true,
users: [{ mode: '', nick: 'nick1', renderName: 'nick1' }]
},
chan2: {
name: 'chan2',
joined: true,
users: []
}
}
@ -109,61 +112,61 @@ describe('channel reducer', () => {
newNick: 'nick3'
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
srv: {
chan1: {
name: 'chan1',
joined: true,
users: [
{ mode: '', nick: 'nick2', renderName: 'nick2' },
{ mode: '', nick: 'nick3', renderName: 'nick3' }
{ mode: '', nick: 'nick3', renderName: 'nick3' },
{ mode: '', nick: 'nick2', renderName: 'nick2' }
]
},
chan2: {
users: [
{ mode: '', nick: 'nick2', renderName: 'nick2' }
]
name: 'chan2',
joined: true,
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
}
}
});
});
it('handles SOCKET_USERS', () => {
const state = reducer(undefined, {
let state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
state = reducer(state, {
type: actions.socket.USERS,
server: 'srv',
channel: 'chan1',
users: [
'user3',
'user2',
'@user4',
'user1',
'+user5'
]
users: ['user3', 'user2', '@user4', 'user1', '+user5']
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
srv: {
chan1: {
name: 'chan1',
joined: true,
users: [
{ mode: 'o', nick: 'user4', renderName: '@user4' },
{ mode: 'v', nick: 'user5', renderName: '+user5' },
{ mode: '', nick: 'user1', renderName: 'user1' },
{ mode: '', nick: 'user3', renderName: 'user3' },
{ mode: '', nick: 'user2', renderName: 'user2' },
{ mode: '', nick: 'user3', renderName: 'user3' }
{ 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, {
let state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
state = reducer(state, {
type: actions.socket.TOPIC,
server: 'srv',
channel: 'chan1',
topic: 'the topic'
});
expect(state.toJS()).toEqual({
expect(state).toMatchObject({
srv: {
chan1: {
topic: 'the topic'
@ -179,7 +182,7 @@ describe('channel reducer', () => {
state = reducer(state, socket_mode('srv', 'chan1', 'nick1', 'o', ''));
expect(state.toJS()).toEqual({
expect(state).toMatchObject({
srv: {
chan1: {
users: [
@ -188,29 +191,25 @@ describe('channel reducer', () => {
]
},
chan2: {
users: [
{ mode: '', nick: 'nick2', renderName: 'nick2' }
]
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
}
}
});
state = reducer(state, socket_mode('srv', 'chan1', 'nick1' ,'v', 'o'));
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.toJS()).toEqual({
expect(state).toMatchObject({
srv: {
chan1: {
users: [
{ mode: 'o', nick: 'nick2', renderName: '@nick2' },
{ mode: 'v', nick: 'nick1', renderName: '+nick1' }
{ mode: 'v', nick: 'nick1', renderName: '+nick1' },
{ mode: 'o', nick: 'nick2', renderName: '@nick2' }
]
},
chan2: {
users: [
{ mode: '', nick: 'nick2', renderName: 'nick2' }
]
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
}
}
});
@ -226,13 +225,13 @@ describe('channel reducer', () => {
]
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
srv: {
chan1: { topic: 'the topic', users: [] },
chan2: { users: [] }
chan1: { name: 'chan1', joined: true, topic: 'the topic', users: [] },
chan2: { name: 'chan2', joined: true, users: [] }
},
srv2: {
chan1: { users: [] }
chan1: { name: 'chan1', joined: true, users: [] }
}
});
});
@ -240,38 +239,38 @@ describe('channel reducer', () => {
it('handles SOCKET_SERVERS', () => {
const state = reducer(undefined, {
type: actions.socket.SERVERS,
data: [
{ host: '127.0.0.1' },
{ host: 'thehost' }
]
data: [{ host: '127.0.0.1' }, { host: 'thehost' }]
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
'127.0.0.1': {},
thehost: {}
});
});
it('optimistically adds the server on CONNECT', () => {
const state = reducer(undefined, connect('127.0.0.1:1337', 'nick', {}));
const state = reducer(
undefined,
connect({ host: '127.0.0.1', nick: 'nick' })
);
expect(state.toJS()).toEqual({
expect(state).toEqual({
'127.0.0.1': {}
});
});
it('removes the server on DISCONNECT', () => {
let state = Immutable.fromJS({
let state = {
srv: {},
srv2: {}
});
};
state = reducer(state, {
type: actions.DISCONNECT,
server: 'srv2'
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
srv: {}
});
});
@ -280,7 +279,8 @@ describe('channel reducer', () => {
function socket_join(server, channel, user) {
return {
type: actions.socket.JOIN,
server, user,
server,
user,
channels: [channel]
};
}
@ -288,6 +288,82 @@ function socket_join(server, channel, user) {
function socket_mode(server, channel, user, add, remove) {
return {
type: actions.socket.MODE,
server, channel, user, add, remove
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': {
name: '#chan1',
users: [],
topic: 'cake'
},
'#pie': {
name: '#pie'
},
'##apples': {
name: '##apples'
}
}
}
})
).toEqual([
{
address: '127.0.0.1',
channels: [
{
name: '##apples'
},
{
name: '#chan1',
users: [],
topic: 'cake'
},
{
name: '#pie'
}
]
},
{
address: 'bob.com',
channels: []
}
]);
});
});

View File

@ -0,0 +1,298 @@
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, date: new Date() },
{ id: 2, date: new Date() }
]
});
expect(state).toMatchObject({
srv: {
'#chan1': [{ id: 1 }, { id: 2 }, { id: 0 }]
}
});
});
it('adds date markers when prepending messages', () => {
let state = {
srv: {
'#chan1': [{ id: 0, date: new Date(1999, 0, 1) }]
}
};
state = reducer(state, {
type: actions.ADD_MESSAGES,
server: 'srv',
tab: '#chan1',
prepend: true,
messages: [
{ id: 1, date: new Date(1990, 0, 2) },
{ id: 2, date: new Date(1990, 0, 3) }
]
});
expect(state).toMatchObject({
srv: {
'#chan1': [
{ id: 1 },
{ type: 'date' },
{ id: 2 },
{ type: 'date' },
{ id: 0 }
]
}
});
});
it('adds a date marker when adding a message', () => {
let state = {
srv: {
'#chan1': [{ id: 0, date: new Date(1999, 0, 1) }]
}
};
state = reducer(state, {
type: actions.ADD_MESSAGE,
server: 'srv',
tab: '#chan1',
message: { id: 1, date: new Date(1990, 0, 2) }
});
expect(state).toMatchObject({
srv: {
'#chan1': [{ id: 0 }, { type: 'date' }, { id: 1 }]
}
});
});
it('adds date markers when adding messages', () => {
let state = {
srv: {
'#chan1': [{ id: 0, date: new Date(1999, 0, 1) }]
}
};
state = reducer(state, {
type: actions.ADD_MESSAGES,
server: 'srv',
tab: '#chan1',
messages: [
{ id: 1, date: new Date(1990, 0, 2) },
{ id: 2, date: new Date(1990, 0, 3) },
{ id: 3, date: new Date(1990, 0, 3) }
]
});
expect(state).toMatchObject({
srv: {
'#chan1': [
{ id: 0 },
{ type: 'date' },
{ id: 1 },
{ type: 'date' },
{ id: 2 },
{ id: 3 }
]
}
});
});
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' }]
}
});
});
it('deletes direct messages when closing a direct message tab', () => {
let state = {
srv: {
bob: [{ content: 'msg1' }, { content: 'msg2' }],
'#chan2': [{ content: 'msg' }]
},
srv2: {
'#chan1': [{ content: 'msg' }]
}
};
state = reducer(state, {
type: actions.CLOSE_PRIVATE_CHAT,
server: 'srv',
nick: 'bob'
});
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)
);
});
});

View File

@ -1,77 +1,96 @@
import Immutable from 'immutable';
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('127.0.0.1:1337', 'nick', {}));
let state = reducer(
undefined,
connect({ host: '127.0.0.1', nick: 'nick' })
);
expect(state.toJS()).toEqual({
expect(state).toEqual({
'127.0.0.1': {
connected: false,
name: '127.0.0.1',
nick: 'nick',
editedNick: null
editedNick: null,
status: {
connected: false,
error: null
},
features: {}
}
});
state = reducer(state, connect('127.0.0.1:1337', 'nick', {}));
state = reducer(state, connect({ host: '127.0.0.1', nick: 'nick' }));
expect(state.toJS()).toEqual({
expect(state).toEqual({
'127.0.0.1': {
connected: false,
name: '127.0.0.1',
nick: 'nick',
editedNick: null
editedNick: null,
status: {
connected: false,
error: null
},
features: {}
}
});
state = reducer(state, connect('127.0.0.2:1337', 'nick', {
name: 'srv'
}));
state = reducer(
state,
connect({ host: '127.0.0.2', nick: 'nick', name: 'srv' })
);
expect(state.toJS()).toEqual({
expect(state).toEqual({
'127.0.0.1': {
connected: false,
name: '127.0.0.1',
nick: 'nick',
editedNick: null
editedNick: null,
status: {
connected: false,
error: null
},
features: {}
},
'127.0.0.2': {
connected: false,
name: 'srv',
nick: 'nick',
editedNick: null
editedNick: null,
status: {
connected: false,
error: null
},
features: {}
}
});
});
it('removes the server on DISCONNECT', () => {
let state = Immutable.fromJS({
let state = {
srv: {},
srv2: {}
});
};
state = reducer(state, {
type: actions.DISCONNECT,
server: 'srv2'
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
srv: {}
});
});
it('handles SET_SERVER_NAME', () => {
let state = Immutable.fromJS({
let state = {
srv: {
name: 'cake'
}
});
};
state = reducer(state, setServerName('pie', 'srv'));
expect(state.toJS()).toEqual({
expect(state).toEqual({
srv: {
name: 'pie'
}
@ -79,7 +98,10 @@ describe('server reducer', () => {
});
it('sets editedNick when editing the nick', () => {
let state = reducer(undefined, connect('127.0.0.1:1337', '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',
@ -87,9 +109,8 @@ describe('server reducer', () => {
editing: true
});
expect(state.toJS()).toEqual({
expect(state).toMatchObject({
'127.0.0.1': {
connected: false,
name: '127.0.0.1',
nick: 'nick',
editedNick: 'nick2'
@ -98,7 +119,10 @@ describe('server reducer', () => {
});
it('clears editedNick when receiving an empty nick after editing finishes', () => {
let state = reducer(undefined, connect('127.0.0.1:1337', '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',
@ -111,9 +135,8 @@ describe('server reducer', () => {
nick: ''
});
expect(state.toJS()).toEqual({
expect(state).toMatchObject({
'127.0.0.1': {
connected: false,
name: '127.0.0.1',
nick: 'nick',
editedNick: null
@ -122,7 +145,10 @@ describe('server reducer', () => {
});
it('updates the nick on SOCKET_NICK', () => {
let state = reducer(undefined, connect('127.0.0.1:1337', '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',
@ -130,9 +156,8 @@ describe('server reducer', () => {
newNick: 'nick2'
});
expect(state.toJS()).toEqual({
expect(state).toMatchObject({
'127.0.0.1': {
connected: false,
name: '127.0.0.1',
nick: 'nick2',
editedNick: null
@ -141,7 +166,10 @@ describe('server reducer', () => {
});
it('clears editedNick on SOCKET_NICK_FAIL', () => {
let state = reducer(undefined, connect('127.0.0.1:1337', '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',
@ -153,9 +181,8 @@ describe('server reducer', () => {
server: '127.0.0.1'
});
expect(state.toJS()).toEqual({
expect(state).toMatchObject({
'127.0.0.1': {
connected: false,
name: '127.0.0.1',
nick: 'nick',
editedNick: null
@ -171,46 +198,83 @@ describe('server reducer', () => {
host: '127.0.0.1',
name: 'stuff',
nick: 'nick',
connected: true
status: {
connected: true
}
},
{
host: '127.0.0.2',
name: 'stuffz',
nick: 'nick2',
connected: false
},
status: {
connected: false
}
}
]
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
'127.0.0.1': {
name: 'stuff',
nick: 'nick',
editedNick: null,
connected: true
status: {
connected: true
},
features: {}
},
'127.0.0.2': {
name: 'stuffz',
nick: 'nick2',
editedNick: null,
connected: false
status: {
connected: false
},
features: {}
}
});
});
it('updates connection status on SOCKET_CONNECTION_UPDATE', () => {
let state = reducer(undefined, connect('127.0.0.1:1337', 'nick', {}));
let state = reducer(
undefined,
connect({ host: '127.0.0.1', nick: 'nick' })
);
state = reducer(state, {
type: actions.socket.CONNECTION_UPDATE,
'127.0.0.1': true
server: '127.0.0.1',
connected: true
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
'127.0.0.1': {
name: '127.0.0.1',
nick: 'nick',
editedNick: null,
connected: true
status: {
connected: true
},
features: {}
}
});
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'
},
features: {}
}
});
});

View File

@ -1,21 +1,19 @@
import reducer, { setSelectedTab } from '../tab';
import * as actions from '../actions';
import { locationChanged } from '../../util/router';
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.toJS()).toEqual({
expect(state).toEqual({
selected: { server: 'srv', name: '#chan' },
history: [
{ server: 'srv', name: '#chan' }
]
history: [{ server: 'srv', name: '#chan' }]
});
state = reducer(state, setSelectedTab('srv', 'user1'));
expect(state.toJS()).toEqual({
expect(state).toEqual({
selected: { server: 'srv', name: 'user1' },
history: [
{ server: 'srv', name: '#chan' },
@ -36,7 +34,7 @@ describe('tab reducer', () => {
channels: ['#chan']
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
selected: { server: 'srv', name: '#chan3' },
history: [
{ server: 'srv1', name: 'bob' },
@ -57,12 +55,12 @@ describe('tab reducer', () => {
nick: 'bob'
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
selected: { server: 'srv', name: '#chan3' },
history: [
{ server: 'srv', name: '#chan' },
{ server: 'srv', name: '#chan' },
{ server: 'srv', name: '#chan3' }
{ server: 'srv', name: '#chan3' }
]
});
});
@ -75,14 +73,12 @@ describe('tab reducer', () => {
state = reducer(state, {
type: actions.DISCONNECT,
server: 'srv',
server: 'srv'
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
selected: { server: 'srv', name: '#chan3' },
history: [
{ server: 'srv1', name: 'bob' },
]
history: [{ server: 'srv1', name: 'bob' }]
});
});
@ -91,27 +87,24 @@ describe('tab reducer', () => {
state = reducer(state, locationChanged('settings'));
expect(state.toJS()).toEqual({
selected: { server: null, name: null },
history: [
{ server: 'srv', name: '#chan' }
]
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,
const state = reducer(
undefined,
locationChanged('chat', {
server: 'srv',
name: '#chan'
})
);
expect(state.toJS()).toEqual({
expect(state).toEqual({
selected: { server: 'srv', name: '#chan' },
history: [
{ server: 'srv', name: '#chan' }
]
history: [{ server: 'srv', name: '#chan' }]
});
});
});

View File

@ -6,6 +6,8 @@ export const KICK = 'KICK';
export const PART = 'PART';
export const SET_TOPIC = 'SET_TOPIC';
export const CHANNEL_SEARCH = 'CHANNEL_SEARCH';
export const INPUT_HISTORY_ADD = 'INPUT_HISTORY_ADD';
export const INPUT_HISTORY_DECREMENT = 'INPUT_HISTORY_DECREMENT';
export const INPUT_HISTORY_INCREMENT = 'INPUT_HISTORY_INCREMENT';
@ -19,8 +21,12 @@ export const FETCH_MESSAGES = 'FETCH_MESSAGES';
export const RAW = 'RAW';
export const UPDATE_MESSAGE_HEIGHT = 'UPDATE_MESSAGE_HEIGHT';
export const OPEN_MODAL = 'OPEN_MODAL';
export const CLOSE_MODAL = 'CLOSE_MODAL';
export const CLOSE_PRIVATE_CHAT = 'CLOSE_PRIVATE_CHAT';
export const OPEN_PRIVATE_CHAT = 'OPEN_PRIVATE_CHAT';
export const PRIVATE_CHATS = 'PRIVATE_CHATS';
export const SEARCH_MESSAGES = 'SEARCH_MESSAGES';
export const TOGGLE_SEARCH = 'TOGGLE_SEARCH';
@ -28,6 +34,7 @@ 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';
@ -36,6 +43,7 @@ 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';
@ -59,7 +67,11 @@ export const socket = createSocketActions([
'cert_fail',
'cert_success',
'channels',
'channel_forward',
'channel_search',
'connection_update',
'error',
'features',
'join',
'message',
'mode',

View File

@ -1,5 +1,4 @@
import { Record } from 'immutable';
import createReducer from 'util/createReducer';
import createReducer from 'utils/createReducer';
import * as actions from './actions';
export const getApp = state => state.app;
@ -9,32 +8,38 @@ export const getCharWidth = state => state.app.charWidth;
export const getWindowWidth = state => state.app.windowWidth;
export const getConnectDefaults = state => state.app.connectDefaults;
const ConnectDefaults = Record({
name: '',
address: '',
channels: [],
ssl: false,
password: false
});
const App = Record({
connected: true,
const initialState = {
connected: false,
wrapWidth: 0,
charWidth: 0,
windowWidth: 0,
connectDefaults: new ConnectDefaults()
});
connectDefaults: {
name: '',
address: '',
channels: [],
ssl: false,
password: false,
readonly: false,
showDetails: false
},
hexIP: false,
newVersionAvailable: false,
installable: null
};
export default createReducer(new App(), {
[actions.APP_SET](state, action) {
return state.set(action.key, action.value);
export default createReducer(initialState, {
[actions.APP_SET](state, { key, value }) {
if (typeof key === 'object') {
Object.assign(state, key);
} else {
state[key] = value;
}
},
[actions.UPDATE_MESSAGE_HEIGHT](state, action) {
return state
.set('wrapWidth', action.wrapWidth)
.set('charWidth', action.charWidth)
.set('windowWidth', action.windowWidth);
state.wrapWidth = action.wrapWidth;
state.charWidth = action.charWidth;
state.windowWidth = action.windowWidth;
}
});
@ -53,7 +58,3 @@ export function setConnected(connected) {
export function setCharWidth(width) {
return appSet('charWidth', width);
}
export function setConnectDefaults(defaults) {
return appSet('connectDefaults', new ConnectDefaults(defaults));
}

View File

@ -0,0 +1,47 @@
import createReducer from 'utils/createReducer';
import * as actions from 'state/actions';
const initialState = {
results: [],
end: false,
topCache: {}
};
export default createReducer(initialState, {
[actions.socket.CHANNEL_SEARCH](state, { results, start, server, q }) {
if (results) {
state.end = false;
if (start > 0) {
state.results.push(...results);
} else {
state.results = results;
if (!q) {
state.topCache[server] = results;
}
}
} else {
state.end = true;
}
},
[actions.OPEN_MODAL](state, { name, payload }) {
if (name === 'channel') {
state.results = state.topCache[payload] || [];
state.end = false;
}
}
});
export function searchChannels(server, q, start) {
return {
type: actions.CHANNEL_SEARCH,
server,
q,
socket: {
type: 'channel_search',
data: { server, q, start }
}
};
}

296
client/js/state/channels.js Normal file
View File

@ -0,0 +1,296 @@
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] = { name: channel, users: [], joined: false };
}
}
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(channels[server], channel => channel.name.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.JOIN](state, { server, channels }) {
channels.forEach(channel => init(state, server, channel));
},
[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].name = channel;
state[server][channel].joined = true;
state[server][channel].users.push(createUser(user));
},
[actions.socket.CHANNEL_FORWARD](state, action) {
init(state, action.server, action.new);
delete state[action.server][action.old];
},
[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 }) {
state[server][channel].users = users.map(nick => loadUser(nick));
},
[actions.socket.TOPIC](state, { server, channel, topic }) {
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].joined = true;
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, getState) => {
const action = {
type: actions.PART,
channels,
server
};
const state = getState().channels[server];
const joined = channels.filter(c => state[c] && state[c].joined);
if (joined.length > 0) {
action.socket = {
type: 'part',
data: {
channels: joined,
server
}
};
}
dispatch(action);
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 }
}
};
}

View File

@ -1,8 +1,10 @@
import { combineReducers } from 'redux';
import app from './app';
import channels from './channels';
import channelSearch from './channelSearch';
import input from './input';
import messages from './messages';
import modals from './modals';
import privateChats from './privateChats';
import search from './search';
import servers from './servers';
@ -18,8 +20,10 @@ export default function createReducer(router) {
router,
app,
channels,
channelSearch,
input,
messages,
modals,
privateChats,
search,
servers,

View File

@ -1,54 +1,45 @@
import { List, Record } from 'immutable';
import createReducer from 'util/createReducer';
import createReducer from 'utils/createReducer';
import * as actions from './actions';
const HISTORY_MAX_LENGTH = 128;
const State = Record({
history: List(),
const initialState = {
history: [],
index: 0
});
};
export const getCurrentInputHistoryEntry = state => {
if (state.input.index === -1) {
return null;
}
return state.input.history.get(state.input.index);
return state.input.history[state.input.index];
};
export default createReducer(new State(), {
[actions.INPUT_HISTORY_ADD](state, action) {
const { line } = action;
if (line.trim() && line !== state.history.get(0)) {
if (history.length === HISTORY_MAX_LENGTH) {
return state.set('history', state.history.unshift(line).pop());
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();
}
return state.set('history', state.history.unshift(line));
state.history.unshift(line);
}
return state;
},
[actions.INPUT_HISTORY_RESET](state) {
return state.set('index', -1);
state.index = -1;
},
[actions.INPUT_HISTORY_INCREMENT](state) {
if (state.index < state.history.size - 1) {
return state.set('index', state.index + 1);
if (state.index < state.history.length - 1) {
state.index++;
}
return state;
},
[actions.INPUT_HISTORY_DECREMENT](state) {
if (state.index >= 0) {
return state.set('index', state.index - 1);
state.index--;
}
return state;
}
});

399
client/js/state/messages.js Normal file
View File

@ -0,0 +1,399 @@
import { createSelector } from 'reselect';
import has from 'lodash/has';
import {
findBreakpoints,
messageHeight,
linkify,
timestamp,
isChannel,
formatDate
} 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] = [];
}
}
let nextID = 0;
function createDateMessage(date) {
const message = {
id: nextID,
type: 'date',
content: formatDate(date),
height: 40
};
nextID++;
return message;
}
function isSameDay(d1, d2) {
return (
d1.getDate() === d2.getDate() &&
d1.getMonth() === d2.getMonth() &&
d1.getFullYear() === d2.getFullYear()
);
}
function reducerPrependMessages(messages, server, tab, state) {
const msgs = [];
for (let i = 0; i < messages.length; i++) {
if (i > 0 && !isSameDay(messages[i - 1].date, messages[i].date)) {
msgs.push(createDateMessage(messages[i].date));
}
msgs.push(messages[i]);
}
const m = state[server][tab];
if (m.length > 0) {
const lastNewMessage = msgs[msgs.length - 1];
const firstMessage = m[0];
if (
firstMessage.date &&
!isSameDay(firstMessage.date, lastNewMessage.date)
) {
msgs.push(createDateMessage(firstMessage.date));
}
}
m.unshift(...msgs);
}
function reducerAddMessage(message, server, tab, state) {
const messages = state[server][tab];
if (messages.length > 0) {
const lastMessage = messages[messages.length - 1];
if (lastMessage.date && !isSameDay(lastMessage.date, message.date)) {
messages.push(createDateMessage(message.date));
}
}
messages.push(message);
}
export default createReducer(
{},
{
[actions.ADD_MESSAGE](state, { server, tab, message }) {
init(state, server, tab);
reducerAddMessage(message, server, tab, state);
},
[actions.ADD_MESSAGES](state, { server, tab, messages, prepend }) {
if (prepend) {
init(state, server, tab);
reducerPrependMessages(messages, server, tab, state);
} else {
if (!messages[0].tab) {
init(state, server, tab);
}
messages.forEach(message => {
if (message.tab) {
init(state, server, message.tab);
}
reducerAddMessage(message, server, message.tab || tab, state);
});
}
},
[actions.DISCONNECT](state, { server }) {
delete state[server];
},
[actions.PART](state, { server, channels }) {
channels.forEach(channel => delete state[server][channel]);
},
[actions.CLOSE_PRIVATE_CHAT](state, { server, nick }) {
delete state[server][nick];
},
[actions.socket.CHANNEL_FORWARD](state, { server, old }) {
if (state[server]) {
delete state[server][old];
}
},
[actions.UPDATE_MESSAGE_HEIGHT](
state,
{ wrapWidth, charWidth, windowWidth }
) {
Object.keys(state).forEach(server =>
Object.keys(state[server]).forEach(target =>
state[server][target].forEach(message => {
if (message.type === 'date') {
return;
}
message.height = messageHeight(
message,
wrapWidth,
charWidth,
6 * charWidth,
windowWidth
);
})
)
);
},
[actions.socket.SERVERS](state, { data }) {
if (data) {
data.forEach(({ host }) => {
state[host] = {};
});
}
}
}
);
function initMessage(message, tab, state) {
if (message.time) {
message.date = new Date(message.time * 1000);
} else {
message.date = new Date();
}
message.time = timestamp(message.date);
if (!message.id) {
message.id = nextID;
nextID++;
}
if (tab.charAt(0) === '#') {
message.channel = true;
}
message.content = message.content || '';
// 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 }
}
};
}

47
client/js/state/modals.js Normal file
View File

@ -0,0 +1,47 @@
import { createSelector } from 'reselect';
import createReducer from 'utils/createReducer';
import * as actions from './actions';
export const getModals = state => state.modals;
export const getHasOpenModals = createSelector(getModals, modals => {
const keys = Object.keys(modals);
for (let i = 0; i < keys.length; i++) {
if (modals[keys[i]].isOpen) {
return true;
}
}
return false;
});
export default createReducer(
{},
{
[actions.OPEN_MODAL](state, { name, payload = {} }) {
state[name] = {
isOpen: true,
payload
};
},
[actions.CLOSE_MODAL](state, { name }) {
state[name].isOpen = false;
}
}
);
export function openModal(name, payload) {
return {
type: actions.OPEN_MODAL,
name,
payload
};
}
export function closeModal(name) {
return {
type: actions.CLOSE_MODAL,
name
};
}

View File

@ -0,0 +1,83 @@
import sortBy from 'lodash/sortBy';
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 (!state[server].includes(nick)) {
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 = state[server]?.findIndex(n => n === nick);
if (i !== -1) {
state[server].splice(i, 1);
}
},
[actions.PRIVATE_CHATS](state, { privateChats }) {
privateChats.forEach(({ server, name }) => {
if (!state[server]) {
state[server] = [];
}
state[server].push(name);
});
},
[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 (dispatch, getState) => {
if (!getState().privateChats[server]?.includes(nick)) {
dispatch({
type: actions.OPEN_PRIVATE_CHAT,
server,
nick,
socket: {
type: 'open_dm',
data: { server, name: nick }
}
});
}
};
}
export function closePrivateChat(server, nick) {
return dispatch => {
dispatch({
type: actions.CLOSE_PRIVATE_CHAT,
server,
nick,
socket: {
type: 'close_dm',
data: { server, name: nick }
}
});
dispatch(updateSelection());
};
}

View File

@ -1,21 +1,20 @@
import { List, Record } from 'immutable';
import createReducer from 'util/createReducer';
import createReducer from 'utils/createReducer';
import * as actions from './actions';
const State = Record({
const initialState = {
show: false,
results: List()
});
results: []
};
export const getSearch = state => state.search;
export default createReducer(new State(), {
[actions.socket.SEARCH](state, action) {
return state.set('results', List(action.results));
export default createReducer(initialState, {
[actions.socket.SEARCH](state, { results }) {
state.results = results || [];
},
[actions.TOGGLE_SEARCH](state) {
return state.set('show', !state.show);
state.show = !state.show;
}
});

View File

@ -1,4 +1,5 @@
import { createSelector } from 'reselect';
import get from 'lodash/get';
import { getServers } from './servers';
import { getSelectedTab } from './tab';
@ -6,5 +7,5 @@ import { getSelectedTab } from './tab';
export const getSelectedTabTitle = createSelector(
getSelectedTab,
getServers,
(tab, servers) => tab.name || servers.getIn([tab.server, 'name'])
(tab, servers) => tab.name || get(servers, [tab.server, 'name'])
);

222
client/js/state/servers.js Normal file
View File

@ -0,0 +1,222 @@
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
},
features: {}
};
}
},
[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 = host, nick, status, features = {} }) => {
state[host] = { name, nick, status, features, editedNick: null };
});
}
},
[actions.socket.CONNECTION_UPDATE](state, { server, connected, error }) {
if (state[server]) {
state[server].status.connected = connected;
state[server].status.error = error;
}
},
[actions.socket.FEATURES](state, { server, features }) {
const srv = state[server];
if (srv) {
srv.features = features;
if (features.NETWORK && srv.name === server) {
srv.name = features.NETWORK;
}
}
}
}
);
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;
}

126
client/js/state/settings.js Normal file
View File

@ -0,0 +1,126 @@
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) {
Object.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
};
}
export function setKey(fileName, key) {
return {
type: actions.SET_KEY,
fileName,
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;
}

122
client/js/state/tab.js Normal file
View File

@ -0,0 +1,122 @@
import get from 'lodash/get';
import Cookie from 'js-cookie';
import createReducer from 'utils/createReducer';
import { push, replace, LOCATION_CHANGED } from 'utils/router';
import * as actions from './actions';
import { find } from '../utils';
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 tabExists(
{ server, name },
{ servers, channels, privateChats }
) {
return (
(name && get(channels, [server, name])) ||
(!name && server && servers[server]) ||
(name && find(privateChats[server], nick => nick === name))
);
}
function parseTabCookie() {
const cookie = Cookie.get('tab');
if (cookie) {
const [server, name = null] = cookie.split(/;(.+)/);
return { server, name };
}
return null;
}
export function updateSelection(tryCookie) {
return (dispatch, getState) => {
const state = getState();
if (tabExists(state.tab.selected, state)) {
return;
}
if (tryCookie) {
const tab = parseTabCookie();
if (tab && tabExists(tab, state)) {
return dispatch(select(tab.server, tab.name, true));
}
}
const { servers } = state;
const { history } = state.tab;
const { server } = state.tab.selected;
const serverAddrs = Object.keys(servers);
if (serverAddrs.length === 0) {
dispatch(replace('/connect'));
} else if (
history.length > 0 &&
tabExists(history[history.length - 1], state)
) {
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
};
}

View File

@ -1,30 +1,29 @@
import { Record } from 'immutable';
import createReducer from 'util/createReducer';
import { LOCATION_CHANGED } from 'util/router';
import createReducer from 'utils/createReducer';
import { LOCATION_CHANGED } from 'utils/router';
import * as actions from './actions';
const State = Record({
const initialState = {
showTabList: false,
showUserList: false
});
};
export const getShowTabList = state => state.ui.showTabList;
export const getShowUserList = state => state.ui.showUserList;
function setMenuHidden(state) {
return state.set('showTabList', false);
state.showTabList = false;
}
export default createReducer(new State(), {
export default createReducer(initialState, {
[actions.TOGGLE_MENU](state) {
return state.update('showTabList', show => !show);
state.showTabList = !state.showTabList;
},
[actions.HIDE_MENU]: setMenuHidden,
[LOCATION_CHANGED]: setMenuHidden,
[actions.TOGGLE_USERLIST](state) {
return state.update('showUserList', show => !show);
state.showUserList = !state.showUserList;
}
});

30
client/js/store.js Normal file
View 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;
}

13
client/js/sw.js Normal file
View File

@ -0,0 +1,13 @@
import { skipWaiting, clientsClaim } from 'workbox-core';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { NavigationRoute, registerRoute } from 'workbox-routing';
skipWaiting();
clientsClaim();
precacheAndRoute(self.__WB_MANIFEST, {
ignoreUrlParametersMatching: [/.*/]
});
const handler = createHandlerBoundToURL('/');
registerRoute(new NavigationRoute(handler));

View File

@ -13,8 +13,7 @@ export default class Socket {
jitter: 0.25
});
this.handlers = [];
this.connect();
this.connected = false;
}
connect() {
@ -26,6 +25,7 @@ export default class Socket {
}, this.connectTimeout);
this.ws.onopen = () => {
this.connected = true;
this.emit('_connected', true);
clearTimeout(this.timeoutConnect);
this.backoff.reset();
@ -33,7 +33,10 @@ export default class Socket {
};
this.ws.onclose = () => {
this.emit('_connected', false);
if (this.connected) {
this.connected = false;
this.emit('_connected', false);
}
clearTimeout(this.timeoutConnect);
clearTimeout(this.timeoutPing);
if (!this.closing) {
@ -50,13 +53,14 @@ export default class Socket {
this.retry();
};
this.ws.onmessage = (e) => {
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);

View 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)
));
});

22
client/js/utils/color.js Normal file
View File

@ -0,0 +1,22 @@
import { hsluvToHex } from 'hsluv';
import fnv1a from '@sindresorhus/fnv1a';
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;
}

View File

@ -0,0 +1,8 @@
import { connect } from 'react-redux';
const strictEqual = (a, b) => a === b;
export default (mapState, mapDispatch) =>
connect(mapState, mapDispatch, null, {
areStatePropsEqual: strictEqual
});

View 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;
};
}

203
client/js/utils/index.js Normal file
View File

@ -0,0 +1,203 @@
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 dateFmt = new Intl.DateTimeFormat(window.navigator.language);
export const formatDate = dateFmt.format;
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 (!Array.isArray(arr) || typeof pred !== 'function') {
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;
}
export function count(arr, pred) {
if (!Array.isArray(arr) || typeof pred !== 'function') {
return 0;
}
let c = 0;
for (let i = 0; i < arr.length; i++) {
if (pred(arr[i])) {
c++;
}
}
return c;
}

View File

@ -7,6 +7,10 @@ const autolinker = new Autolinker({
});
export default function linkify(text) {
if (!text) {
return text;
}
let matches = autolinker.parseText(text);
if (matches.length === 0) {
@ -30,12 +34,20 @@ export default function linkify(text) {
}
result.push(
<a target="_blank" rel="noopener noreferrer" href={match.getAnchorHref()}>
<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);
result[result.length - 1] += text.slice(
pos,
match.offset + match.matchedText.length
);
} else {
result.push(text.slice(pos, match.offset + match.matchedText.length));
}

View File

@ -18,7 +18,13 @@ export function findBreakpoints(text) {
return breakpoints;
}
export function messageHeight(message, wrapWidth, charWidth, indent = 0, windowWidth) {
export function messageHeight(
message,
wrapWidth,
charWidth,
indent = 0,
windowWidth
) {
let pad = (6 + (message.from ? message.from.length + 1 : 0)) * charWidth;
let height = lineHeight + 8;
@ -26,7 +32,7 @@ export function messageHeight(message, wrapWidth, charWidth, indent = 0, windowW
wrapWidth -= userListWidth;
}
if (pad + (message.length * charWidth) < wrapWidth) {
if (pad + message.length * charWidth < wrapWidth) {
return height;
}
@ -35,7 +41,7 @@ export function messageHeight(message, wrapWidth, charWidth, indent = 0, windowW
let prevPos = 0;
for (let i = 0; i < breaks.length; i++) {
if (pad + ((breaks[i].end - prevBreak) * charWidth) >= wrapWidth) {
if (pad + (breaks[i].end - prevBreak) * charWidth >= wrapWidth) {
prevBreak = prevPos;
pad = indent;
height += lineHeight;
@ -44,7 +50,7 @@ export function messageHeight(message, wrapWidth, charWidth, indent = 0, windowW
prevPos = breaks[i].next;
}
if (pad + ((message.length - prevBreak) * charWidth) >= wrapWidth) {
if (pad + (message.length - prevBreak) * charWidth >= wrapWidth) {
height += lineHeight;
}

View File

@ -1,8 +1,6 @@
import createHistory from 'history/createBrowserHistory';
import history from 'history/browser';
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';
@ -71,7 +69,7 @@ function match(routes, location) {
for (let j = 0; j < keys.length; j++) {
params[keys[j]] = decodeURIComponent(params[keys[j]]);
}
return locationChanged(routes[i].name, params, decode(location));
return locationChanged(routes[i].name, params, decode({ ...location }));
}
}
return null;
@ -97,9 +95,12 @@ export default function initRouter(routes, store) {
matched = { location: {} };
}
history.listen(location => {
history.listen(({ location }) => {
const nextMatch = match(patterns, location);
if (nextMatch && nextMatch.location.pathname !== matched.location.pathname) {
if (
nextMatch &&
nextMatch.location.pathname !== matched.location.pathname
) {
matched = nextMatch;
store.dispatch(matched);
}

Some files were not shown because too many files have changed in this diff Show More