Compare commits

...

342 Commits

Author SHA1 Message Date
Ken-Håvard Lieng
d3d8323646
Add irc channel 2022-01-14 15:20:11 +01:00
Ken-Håvard Lieng
40fba768d7
Merge pull request #97 from daftaupe/patch-1
Updating default connection to Libera.Chat
2022-01-14 15:14:01 +01:00
Pierre-Alain TORET
4b69a1dff4
Updating default connection to Libera.Chat 2022-01-14 15:07:45 +01:00
Ken-Håvard Lieng
668858dfec
Merge pull request #86 from t0xic0der/restart-policy
Added restart policy and detach mode
2021-05-30 19:16:02 +02:00
Akashdeep Dhar
8cc1514f76 Added restart policy and detach mode 2021-05-30 22:37:14 +05:30
Ken-Håvard Lieng
721492cae2
Merge pull request #71 from eyedeekay/optimized-defaults
Optimized defaults for I2P Tunnels
2020-12-10 09:06:08 +01:00
idk
2e48554b26
remove commented-out cryptix branch 2020-12-07 12:21:33 -05:00
idk
5e5bbe8268
revert changes to assets/bindata.go 2020-12-07 12:20:22 -05:00
idk
be64fe5aae
remove cryptix/goSam 2020-12-07 12:14:46 -05:00
idk
25879ef498
Set optimized I2P defaults 2020-12-07 01:50:07 -05:00
idk
065c86ccff
Set optimized I2P defaults 2020-12-07 01:49:03 -05:00
idk
443875e921
Set optimized I2P defaults 2020-12-07 01:46:53 -05:00
Ken-Håvard Lieng
5d9f633fc9
Merge pull request #70 from eyedeekay/master
Another goSam version update
2020-11-25 09:55:44 +01:00
idk
19fea710e9
Another goSam version update 2020-11-23 20:47:57 -05:00
Ken-Håvard Lieng
cfd51f1e59
Merge pull request #69 from eyedeekay/i2pecies
Update goSam library to 0.32.28
2020-11-13 09:16:00 +01:00
Ken-Håvard Lieng
8184f339a7 Use node LTS on travis 2020-11-13 08:59:36 +01:00
idk
8ba86fa654
Add missing files/dirs 2020-11-12 23:17:41 -05:00
idk
04f851eeb6
Actually, do 0.32.28 instead 2020-11-12 22:53:16 -05:00
idk
edc20572c7
update vendor files 2020-11-12 20:24:39 -05:00
idk
03e1349058
update goSam version to 0.32.27 2020-11-12 20:21:16 -05:00
Ken-Håvard Lieng
a52ddf3033
Merge pull request #67 from andwun/fix/issue-66
client: Downgraded @sindresorhus/fnv1a to v1.2.0 to fix #66
2020-09-17 01:06:30 +02:00
Ken-Håvard Lieng
c75eb4abd5 Update travis badge URL 2020-09-17 01:04:57 +02:00
Andreas Wunderlich
f0f394e5cc client: Downgraded @sindresorhus/fnv1a to v1.2.0 to fix #66 2020-09-09 01:25:36 +02:00
Ken-Håvard Lieng
23ac65b402
Merge pull request #65 from khlieng/dependabot/npm_and_yarn/client/elliptic-6.5.3
Bump elliptic from 6.5.2 to 6.5.3 in /client
2020-07-30 20:00:29 +02:00
dependabot[bot]
64aebe3505
Bump elliptic from 6.5.2 to 6.5.3 in /client
Bumps [elliptic](https://github.com/indutny/elliptic) from 6.5.2 to 6.5.3.
- [Release notes](https://github.com/indutny/elliptic/releases)
- [Commits](https://github.com/indutny/elliptic/compare/v6.5.2...v6.5.3)

Signed-off-by: dependabot[bot] <support@github.com>
2020-07-30 17:42:14 +00:00
Ken-Håvard Lieng
b92a9d2e5b Update vendor 2020-07-30 09:29:50 +02:00
Ken-Håvard Lieng
27142cc5c7
Merge pull request #64 from eyedeekay/i2p-support
I2p support
2020-07-30 08:44:50 +02:00
idk
8f18eaa4cf Remove debugging message 2020-07-29 23:22:17 -04:00
idk
f997149dd6 how awesome is that! 2020-07-29 23:04:13 -04:00
idk
a02ad3a299 try it with goSam 2020-07-29 22:28:34 -04:00
Ken-Håvard Lieng
c08d750bf2
Merge pull request #63 from khlieng/dependabot/npm_and_yarn/client/lodash-4.17.19
Bump lodash from 4.17.15 to 4.17.19 in /client
2020-07-17 08:23:49 +02:00
dependabot[bot]
5aced46020
Bump lodash from 4.17.15 to 4.17.19 in /client
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.15 to 4.17.19.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.15...4.17.19)

Signed-off-by: dependabot[bot] <support@github.com>
2020-07-17 06:12:04 +00:00
Ken-Håvard Lieng
ea4f321fe7 Collapse nick changes 2020-07-05 08:32:29 +02:00
Ken-Håvard Lieng
1fe4c4d17e Format topic 2020-06-30 13:28:51 +02:00
Ken-Håvard Lieng
307573830a Render text blocks 2020-06-30 13:24:23 +02:00
Ken-Håvard Lieng
ca4db66308 Add __Host- prefix, set X-XSS-Protection to 0, require go1.11 2020-06-25 08:35:15 +02:00
Ken-Håvard Lieng
d844f6ee1a Combine init actions 2020-06-25 01:50:10 +02:00
Ken-Håvard Lieng
02e9df865e Show DCC send filesize 2020-06-24 08:09:05 +02:00
Ken-Håvard Lieng
45f8795fad Stop trimming SASL and server passwords 2020-06-24 07:46:13 +02:00
Ken-Håvard Lieng
e0ca9d5d8c Fix lastMessages map init in LoadUsers() 2020-06-22 17:22:10 +02:00
Ken-Håvard Lieng
972f568a00 Fix bad nick test 2020-06-21 06:07:32 +02:00
Ken-Håvard Lieng
b9f52a8761 Select channel when joining through UI 2020-06-21 05:33:02 +02:00
Ken-Håvard Lieng
ca23b3ded8 Improve error routing, fix dm tab not opening 2020-06-21 05:13:38 +02:00
Ken-Håvard Lieng
1c996822cd Style scrollbars 2020-06-20 07:41:01 +02:00
Ken-Håvard Lieng
f89e6ae133 Darken hashtags in channel list 2020-06-19 04:38:26 +02:00
Ken-Håvard Lieng
4694e66e98 Ignore hashtags when sorting channels 2020-06-19 03:58:08 +02:00
Ken-Håvard Lieng
fc937aaac8 Update client dependencies 2020-06-19 03:02:42 +02:00
Ken-Håvard Lieng
fd5e50a2cb Add DescribeTLS() 2020-06-18 09:01:29 +02:00
Ken-Håvard Lieng
04e6e8c7a2 Bind identd to config address, set read/write deadlines in ident.Server, only reply to ident queries where the remote hosts match 2020-06-17 03:19:20 +02:00
Ken-Håvard Lieng
15ee5ce1c9 Use small buffer for ident query 2020-06-16 12:01:07 +02:00
Ken-Håvard Lieng
e0d2243248 Add identd 2020-06-16 11:28:47 +02:00
Ken-Håvard Lieng
67fe5d263d Add SOCKS5 proxy support 2020-06-16 03:04:27 +02:00
Ken-Håvard Lieng
7040f1c8d0 Use mutex pointer in network state 2020-06-16 01:29:35 +02:00
Ken-Håvard Lieng
2ea4584c97 Add auto_ctcp config option 2020-06-16 01:22:23 +02:00
Ken-Håvard Lieng
fcf0c17682 Update dependencies 2020-06-15 11:05:32 +02:00
Ken-Håvard Lieng
6985dd16da Handle kick, rename server to network 2020-06-15 10:58:51 +02:00
Ken-Håvard Lieng
a33157ff84 Return false from socket handlers to not dispatch action 2020-06-05 08:56:11 +02:00
Ken-Håvard Lieng
a4fe18c0f0 Update client dependencies 2020-06-04 08:09:59 +02:00
Ken-Håvard Lieng
9d8d04fa7c Filter SASL mechanisms on RPL_SASLMECHS without trying next one 2020-06-04 05:06:59 +02:00
Ken-Håvard Lieng
876d9ebdd0 Implement SCRAM-SHA-256 2020-06-04 02:28:41 +02:00
Ken-Håvard Lieng
ead3b37cf9 Collapse and log join, part and quit, closes #27, log nick and topic changes, move state into irc package 2020-06-03 03:04:38 +02:00
Ken-Håvard Lieng
edd4d6eadb Disable cgo in install.sh 2020-05-25 01:25:05 +02:00
Ken-Håvard Lieng
e76beca4a0 Parse ident and host, rename irc.Message.Nick to Sender 2020-05-24 11:09:59 +02:00
Ken-Håvard Lieng
8829793290 Append clientWantedCaps 2020-05-24 07:22:13 +02:00
Ken-Håvard Lieng
71b2136a9e Update dependencies 2020-05-24 07:21:47 +02:00
Ken-Håvard Lieng
e97c7f2ada Pass config struct into irc.Client 2020-05-23 09:42:20 +02:00
Ken-Håvard Lieng
9aac4f4e29 Update README 2020-05-23 08:28:32 +02:00
Ken-Håvard Lieng
2f8dad2529 Add SASL auth and CAP negotiation 2020-05-23 08:05:37 +02:00
Ken-Håvard Lieng
be8b785813 Scrape horse doc constants, handle all nick collision error types 2020-05-23 02:30:48 +02:00
Ken-Håvard Lieng
e937f5d8b9 Quit on ERROR 2020-05-22 01:22:08 +02:00
Ken-Håvard Lieng
99b3ff519b Remember last used nick and realname, closes #43 2020-05-21 05:57:05 +02:00
Ken-Håvard Lieng
35727fb2b8 Fix dm tab being opened on server messages 2020-05-21 05:24:26 +02:00
Ken-Håvard Lieng
1abe280957 Set timeout and deadline in DownloadDCC 2020-05-20 08:38:18 +02:00
Ken-Håvard Lieng
e33b9f05e4 Implement DCC streaming 2020-05-20 07:21:12 +02:00
Ken-Håvard Lieng
973578bb49 Handle common CTCP messages 2020-05-20 04:19:40 +02:00
Ken-Håvard Lieng
4816fbfbca Fetch scrollback messages in dm tabs 2020-05-20 00:30:44 +02:00
Ken-Håvard Lieng
f0eada0f75 Remove openDMs when deleting user 2020-05-20 00:23:16 +02:00
Ken-Håvard Lieng
abbe739b04 Update README 2020-05-19 10:48:54 +02:00
Ken-Håvard Lieng
63afd839be
Merge pull request #62 from pidario/feat/dcc-support
start of DCC implementation
2020-05-19 10:44:07 +02:00
Ken-Håvard Lieng
84a10efe36 Log key dcc info messages, keep dcc tab open 2020-05-19 10:37:20 +02:00
Ken-Håvard Lieng
902e4da46f Remove fontfaceobserver 2020-05-19 01:29:22 +02:00
Ken-Håvard Lieng
e05118a29b Move script tags 2020-05-18 11:53:29 +02:00
Ken-Håvard Lieng
a90e8d4b2f Improve speed calculation, clean some things up 2020-05-18 03:32:57 +02:00
Ken-Håvard Lieng
2d68f04ab2 Load client cert with LoadX509KeyPair 2020-05-18 00:36:15 +02:00
Ken-Håvard Lieng
b92f5cfb43 Send download link on completion 2020-05-17 06:34:59 +02:00
Ken-Håvard Lieng
fa99a96733 Create download directory in NewUser 2020-05-17 02:31:50 +02:00
Ken-Håvard Lieng
6b5bf4ced1 Add per-user download directory 2020-05-17 02:14:35 +02:00
Ken-Håvard Lieng
0c902f8ac8 Render IRC colors and formatting, closes #46 2020-05-16 08:25:58 +02:00
Ken-Håvard Lieng
ed432881ef Push connect chunks 2020-05-16 03:58:17 +02:00
Ken-Håvard Lieng
75c9560dfb Handle nil and different types in stateData 2020-05-16 02:33:38 +02:00
Dario Piombo
1532b2a8c8 changed sendJson param and removed not needed file mode
removed instantaneous speed; update only if percentage delta > 0.1

removed instantaneous speed; update only if percentage delta > 0.1
2020-05-12 16:01:17 +02:00
Ken-Håvard Lieng
4b8491cf99 Make TextInput label real, add aria-label to icon buttons 2020-05-12 07:48:12 +02:00
Ken-Håvard Lieng
2509420ba5 Make ToCTCP handle any type of CTCP message, move DCC handling to separate file 2020-05-12 04:13:05 +02:00
Dario Piombo
ed2e56948e start of DCC implementation
(server side)

small refactoring and added speed calculation

fixup! small refactoring and added speed calculation

download progress

fixup! download progress
2020-05-11 17:34:37 +02:00
Ken-Håvard Lieng
9581a63e81 Ignore empty channel lists 2020-05-11 14:13:36 +02:00
Ken-Håvard Lieng
8fa91ac470 Use string port 2020-05-10 02:53:39 +02:00
Ken-Håvard Lieng
eb7545455c Add jsconfig.json 2020-05-10 01:35:58 +02:00
Ken-Håvard Lieng
eab788a782 Enable overriding connect defaults with query params, closes #49 2020-05-08 10:26:32 +02:00
Ken-Håvard Lieng
dcbf3397c1 Use latest node on travis 2020-05-08 04:16:41 +02:00
Ken-Håvard Lieng
1773fef8ef Update gulpfile 2020-05-08 04:16:23 +02:00
Ken-Håvard Lieng
08ffc79a65 Remove local messages when closing dm tab, avoid sending open_dm if already open 2020-05-08 02:56:54 +02:00
Ken-Håvard Lieng
2a72b198e3 Update dependencies 2020-05-08 02:10:22 +02:00
Ken-Håvard Lieng
0d085a2b4d Clear prevSearch when closing modal 2020-05-07 08:10:25 +02:00
Ken-Håvard Lieng
497f9e882c Unvendor fnv1a 2020-05-06 06:50:53 +02:00
Ken-Håvard Lieng
7d97d10e76 Open dm tab on /msg 2020-05-06 04:50:27 +02:00
Ken-Håvard Lieng
8305dd561d Log direct messages and keep track of open direct message tabs 2020-05-06 04:19:55 +02:00
Ken-Håvard Lieng
e97bb519ed
Merge pull request #61 from nhandler/patch-1
Replace Freenode with freenode
2020-05-05 07:26:38 +02:00
Nathan Handler
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
Nathan Handler
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
Ken-Håvard Lieng
79af695d17 Add apple-touch-icon 2020-05-05 03:34:36 +02:00
Ken-Håvard Lieng
d98312f99b Cache manifest.json 2020-05-05 03:31:14 +02:00
Ken-Håvard Lieng
010bb6a102 Sleep before first reconnect attempt 2020-05-05 01:35:05 +02:00
Ken-Håvard Lieng
530e08b9ee Convert withModal to useModal 2020-05-03 09:05:16 +02:00
Ken-Håvard Lieng
9cf42df1ea Remove channel from reconnect list when parting 2020-05-01 05:40:49 +02:00
Ken-Håvard Lieng
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
Ken-Håvard Lieng
3d7011e504 Add vscode to config command editor stack and enable passing in an arbitrary editor 2020-05-01 04:31:20 +02:00
Ken-Håvard Lieng
3d2e443108 Pass all unknown commands through to the IRC server, closes #56 2020-05-01 02:12:21 +02:00
Ken-Håvard Lieng
b002eef285 Fix navicon 2020-04-30 14:36:30 +02:00
Ken-Håvard Lieng
c566d5d61d Copy location object 2020-04-30 13:44:36 +02:00
Ken-Håvard Lieng
13a31c30d9 Update .goreleaser.yml 2020-04-30 08:16:06 +02:00
Ken-Håvard Lieng
508a41ee45 Update client dependencies 2020-04-30 07:54:30 +02:00
Ken-Håvard Lieng
1794e2680a Update server dependencies 2020-04-29 04:23:32 +02:00
Ken-Håvard Lieng
c704ebb042 Use react-icons 2020-04-29 03:13:35 +02:00
Ken-Håvard Lieng
bb66740fd1 Update gulp instructions in README 2020-04-24 03:04:46 +02:00
Ken-Håvard Lieng
4010132884 Linkify topics in channel joining modal 2020-04-24 02:37:56 +02:00
Ken-Håvard Lieng
77543e3aed Switch to bbolt 2020-04-23 01:06:36 +02:00
Ken-Håvard Lieng
360bed00f9 Implement old storage.Path API 2020-04-20 03:02:15 +02:00
Ken-Håvard Lieng
164e071e7f Update README 2020-04-20 02:15:57 +02:00
Ken-Håvard Lieng
01914f070d Turn modules off when installing go-bindata on travis 2020-04-20 02:07:12 +02:00
Ken-Håvard Lieng
00e40dc153 Update go.mod and modules.txt format 2020-04-20 01:38:06 +02:00
Ken-Håvard Lieng
47efab2e56 Update .travis.yml 2020-04-20 01:27:25 +02:00
Ken-Håvard Lieng
c171a620e0
Merge pull request #58 from daftaupe/configpath
Allow dispatch to store data and configuration separately
2020-04-19 20:30:34 +02:00
Pierre-Alain TORET
ca81475fa5 Add option --config and --data to specify where to store the configuration and the data 2020-03-20 18:24:17 +01:00
Ken-Håvard Lieng
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
dependabot[bot]
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
Ken-Håvard Lieng
855f4d3e64 Stop using pointers for nested config structs, closes #41 2019-06-09 02:29:35 +02:00
Ken-Håvard Lieng
540efa03c4 Update dependencies 2019-06-09 02:01:48 +02:00
Ken-Håvard Lieng
7ad76273c0 Fix MessageBox scroll stutter when state updates while close to the bottom 2019-02-08 09:28:55 +01:00
Ken-Håvard Lieng
c1e1f2c327 Update dependencies 2019-02-08 09:10:06 +01:00
Ken-Håvard Lieng
4eda7ef396 Fix getSortedChannels test 2019-02-08 08:56:21 +01:00
Ken-Håvard Lieng
fad2e030d4 Fix h2 push hash check 2019-02-01 06:39:38 +01:00
Ken-Håvard Lieng
3e90e6c86d Only count joined channels 2019-01-30 04:48:37 +01:00
Ken-Håvard Lieng
71bfe92dae Update dependencies 2019-01-30 03:51:13 +01:00
Ken-Håvard Lieng
613d9fca6e Send irc features to the client 2019-01-27 08:53:07 +01:00
Ken-Håvard Lieng
9267c661dc Timeout channel list updates 2019-01-25 11:24:57 +01:00
Ken-Håvard Lieng
f8e12f5938 Handle channel forwarding and errors better 2019-01-25 11:02:31 +01:00
Ken-Håvard Lieng
497934888c Fix channel reducer tests 2019-01-25 08:36:21 +01:00
Ken-Håvard Lieng
24960f23b9 Add topic modal 2019-01-25 03:57:58 +01:00
Ken-Håvard Lieng
aab1ad3e99 Fix h2 push 2019-01-25 02:32:22 +01:00
Ken-Håvard Lieng
815b518c2c Update dependencies 2019-01-23 08:52:17 +01:00
Ken-Håvard Lieng
5e674254f0 Use pointer receiver in stateData 2019-01-23 08:20:16 +01:00
Ken-Håvard Lieng
24b26aa85f Add channel joining UI, closes #37 2019-01-23 07:34:39 +01:00
Ken-Håvard Lieng
f25594e962 Add casefolding to irc lib 2019-01-13 05:10:11 +01:00
Ken-Håvard Lieng
075e404079 Reset backoff on RPL_WELCOME 2019-01-11 05:00:15 +01:00
Ken-Håvard Lieng
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
Ken-Håvard Lieng
a3618b97ae Add list command 2019-01-11 02:46:46 +01:00
Ken-Håvard Lieng
e4d5d2737b Use strings.Replacer to unescape tags 2019-01-11 02:19:57 +01:00
Ken-Håvard Lieng
0085cea5a1 Add react-modal, replace confirm usage with it 2019-01-05 07:08:34 +01:00
Ken-Håvard Lieng
63cf65100d Pull https handling out into a new package 2018-12-31 03:33:05 +01:00
Ken-Håvard Lieng
67e32661f1 Update dependencies 2018-12-31 02:20:22 +01:00
Ken-Håvard Lieng
95eff71e2e Add go 1.12beta1 travis build 2018-12-21 01:53:35 +01:00
Ken-Håvard Lieng
8526805c2f Add headers config, closes #25 2018-12-20 11:51:31 +01:00
Ken-Håvard Lieng
6aaa2b521d Avoid sending join when the channels input is empty 2018-12-19 03:09:13 +01:00
Ken-Håvard Lieng
0d9290d037 Update client dependencies 2018-12-19 02:55:50 +01:00
Ken-Håvard Lieng
6fedb23363 Prerender index page 2018-12-17 14:44:46 +01:00
Ken-Håvard Lieng
fc643483be Dont redirect private IPs and localhost 2018-12-17 12:45:33 +01:00
Ken-Håvard Lieng
6c3a5777c4 Use certmagic, simplify config, set HTTP timeouts and a modern TLSConfig 2018-12-16 12:32:03 +01:00
Ken-Håvard Lieng
c5a9a5b1c1 Print go version 2018-12-15 11:30:29 +01:00
Ken-Håvard Lieng
6a816fbff6 Add date marker tests 2018-12-15 11:20:49 +01:00
Ken-Håvard Lieng
3c105c493b Handle messages with no content, improve prepend perf 2018-12-15 11:09:57 +01:00
Ken-Håvard Lieng
50d735aaa3 Add date markers 2018-12-14 14:24:23 +01:00
Ken-Håvard Lieng
34d89c75b2 Use correct gulp version on travis 2018-12-11 11:17:05 +01:00
Ken-Håvard Lieng
71f79fd84e Pass in config struct 2018-12-11 10:54:05 +01:00
Ken-Håvard Lieng
8f1105bc59 Only attempt to maintain scroll position when prepending messages if there was previously any messages 2018-12-08 11:56:02 +01:00
Ken-Håvard Lieng
0e46fbcc82 Clean up initialState module 2018-12-08 11:25:08 +01:00
Ken-Håvard Lieng
c1ca29511e Simplify routing logic 2018-12-08 11:08:01 +01:00
Ken-Håvard Lieng
35c2d682e3 Improve routing 2018-12-07 08:48:40 +01:00
Ken-Håvard Lieng
aca380629f Update dotfiles 2018-12-06 11:05:10 +01:00
Ken-Håvard Lieng
007fc80e72 Update dependencies 2018-12-06 11:03:03 +01:00
Ken-Håvard Lieng
cca3f5bc93 Use stable readme download links 2018-12-02 11:31:35 +01:00
Ken-Håvard Lieng
f05e405fb1 Embed version info in docker build 2018-12-02 07:39:23 +01:00
Ken-Håvard Lieng
73205b64f6 v0.5.4 2018-11-29 13:07:27 +01:00
Ken-Håvard Lieng
5861a54dfc Improve 404 handling 2018-11-29 13:06:37 +01:00
Ken-Håvard Lieng
869713d236 Fix initial scroll position sometimes being off 2018-11-29 12:05:42 +01:00
Ken-Håvard Lieng
0438a099cf Fix dev mode, turn off react concurrent mode, update dependencies 2018-11-29 11:54:05 +01:00
Ken-Håvard Lieng
df71c54d37 Use a map to serve files 2018-11-27 12:07:48 +01:00
Ken-Håvard Lieng
d24d33d94c Fix push cookie hash check 2018-11-27 11:34:02 +01:00
Ken-Håvard Lieng
57704c9e89 v0.5.3 2018-11-26 02:09:29 +01:00
Ken-Håvard Lieng
dd03e75be4 Add amd64 and darwin archive name replacements 2018-11-26 02:07:41 +01:00
Ken-Håvard Lieng
4eac0609c2 Add bottom margin to settings version 2018-11-26 02:05:21 +01:00
Ken-Håvard Lieng
bf2e7875a5 Add version flags and command, closes #38 2018-11-26 01:58:24 +01:00
Ken-Håvard Lieng
fbbcf6457e Show version info in settings 2018-11-22 12:08:18 +01:00
Ken-Håvard Lieng
5d896ae439 Print prettier version info 2018-11-22 11:31:02 +01:00
Ken-Håvard Lieng
9b40934654 Grab referer in /init handler instead of getIndexData() 2018-11-22 10:40:29 +01:00
Ken-Håvard Lieng
bd0541120f Improve document.title handling 2018-11-22 10:09:13 +01:00
Ken-Håvard Lieng
09a1933131 Increase scrollbackDebounce to 150 2018-11-22 09:51:26 +01:00
Ken-Håvard Lieng
8eb1f9cbb4 Fix some messages not rendering on MessageBox mount, handle scroll restoration edge case 2018-11-22 09:50:38 +01:00
Ken-Håvard Lieng
9ca50b1546 v0.5.2 2018-11-22 08:48:29 +01:00
Ken-Håvard Lieng
0699fc287d Fix scroll jumping on MessageBox mount 2018-11-22 08:48:29 +01:00
Ken-Håvard Lieng
937480bfd4 Prevent rounded input corners in Safari 2018-11-22 08:48:29 +01:00
Ken-Håvard Lieng
05527e41b7 Use absolute paths 2018-11-22 08:48:29 +01:00
Ken-Håvard Lieng
65e103fd23
Delete release.sh 2018-11-21 02:17:51 +01:00
Ken-Håvard Lieng
2a7b7572fa Update readme download links 2018-11-17 12:48:15 +01:00
Ken-Håvard Lieng
2c1a6f2c44 Discard git changes when doing a release on travis 2018-11-17 12:34:12 +01:00
Ken-Håvard Lieng
96f18117bd v0.5.1 2018-11-17 12:22:28 +01:00
Ken-Håvard Lieng
90785aba20 Create sessions on boot requests instead of websocket handshakes 2018-11-17 11:52:36 +01:00
Ken-Håvard Lieng
da87dccb53 Update react-hot-loader to 4.4.0, turn on pureSFC 2018-11-17 11:12:30 +01:00
Ken-Håvard Lieng
b54cb42426 Setup goreleaser 2018-11-17 10:32:02 +01:00
Ken-Håvard Lieng
4dcf674c4b Add robots.txt, clean up index template 2018-11-14 10:11:15 +01:00
Ken-Håvard Lieng
764475b2a5 Turn on terserOptions.safari10 2018-11-14 09:24:40 +01:00
Ken-Håvard Lieng
d867ca8477 Add worker-src csp directive 2018-11-14 08:34:35 +01:00
Ken-Håvard Lieng
a783a87d04 Set overscanCount to 5 2018-11-14 08:33:01 +01:00
Ken-Håvard Lieng
a7b6442ed9 Update dependencies 2018-11-14 08:25:20 +01:00
Ken-Håvard Lieng
374604fae2 v0.5 2018-11-11 07:08:53 +01:00
Ken-Håvard Lieng
48f59604a6 Update readme lib list 2018-11-10 12:56:31 +01:00
Ken-Håvard Lieng
474afda9c2 Add manifest.json, icons and install button, flatten client/src 2018-11-10 12:33:44 +01:00
Ken-Håvard Lieng
a219e689c1 Update vendor dir 2018-11-10 08:04:36 +01:00
Ken-Håvard Lieng
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
Ken-Håvard Lieng
04852cdf58 Implement http.Handler in server.Dispatch 2018-11-09 07:32:47 +01:00
Ken-Håvard Lieng
4b4b2394a9 Link rel preload boot data 2018-11-09 07:12:43 +01:00
Ken-Håvard Lieng
9b6844449d Vendor workbox 2018-11-08 09:39:32 +01:00
Ken-Håvard Lieng
9a5d7f8360 Exclude inline chunks from precache manifest 2018-11-08 08:57:24 +01:00
Ken-Håvard Lieng
70b2c4df47 Dont refresh session keys on bootloader requests 2018-11-08 08:39:47 +01:00
Ken-Håvard Lieng
f86e0d9283 Dont do auth on service worker index page requests 2018-11-07 02:55:00 +01:00
Ken-Håvard Lieng
fd6c8a70e2 Append pathname to bootloader request 2018-11-07 02:07:23 +01:00
Ken-Håvard Lieng
ed40b956b7 Set publicPath in production webpack config 2018-11-07 01:35:53 +01:00
Ken-Håvard Lieng
ca222ff10d Add cache-first service worker 2018-11-06 11:13:32 +01:00
Ken-Håvard Lieng
b2b5f82486 Shallow render linkify test 2018-11-05 08:23:22 +01:00
Ken-Håvard Lieng
69d5f41270 Fix message rendering 2018-11-05 07:11:15 +01:00
Ken-Håvard Lieng
d930365eeb Code split the client, update dependencies 2018-11-04 07:23:07 +01:00
Ken-Håvard Lieng
84c3d5cc88
Merge pull request #35 from diadara/patch-2
Update readme
2018-11-01 22:06:19 +01:00
Nithin Saji
ef34baf5a0
Update readme
Make instructions for starting dev environment explicit
2018-10-31 15:49:41 +07:00
Ken-Håvard Lieng
38ed5a367b Make sure list has mounted before using ref 2018-10-26 08:18:31 +02:00
Ken-Håvard Lieng
4482dd33ce Migrate from react-virtualized to react-window 2018-10-26 07:00:37 +02:00
Ken-Håvard Lieng
675e350da3 Use Cache-Control immutable and SameSite Lax 2018-10-19 02:11:12 +02:00
Ken-Håvard Lieng
7658e3bde7 Avoid dispatching unneeded socket actions 2018-10-16 01:04:49 +02:00
Ken-Håvard Lieng
7fb0cd3e6a Send default settings when there is no user yet 2018-10-15 09:06:43 +02:00
Ken-Håvard Lieng
6c6a9e12cf Add colored nicks settings option 2018-10-15 08:56:17 +02:00
Ken-Håvard Lieng
ec03db4db6 Remove base64-arraybuffer 2018-10-10 21:23:42 +02:00
Ken-Håvard Lieng
afc80650e7 Use HSLuv for nick colors 2018-10-08 01:34:53 +02:00
Ken-Håvard Lieng
6146b27adc Update readme 2018-10-07 01:27:26 +02:00
Ken-Håvard Lieng
973aa3b104 Bust dat screenshot cache 2018-10-07 01:15:09 +02:00
Ken-Håvard Lieng
6f6dfca5fb Move "Add network" button down 2018-10-07 01:13:58 +02:00
Ken-Håvard Lieng
b3f2b53a6f Add colored nicks 2018-10-07 00:25:56 +02:00
Ken-Håvard Lieng
937987da82 Drop go 1.9 support 2018-10-06 09:17:59 +02:00
Ken-Håvard Lieng
91fd50fe10 Make gen:install work outside GOPATH 2018-10-06 09:15:11 +02:00
Ken-Håvard Lieng
3ec450805b Set SameSite Strict on session cookies 2018-10-06 08:56:29 +02:00
Ken-Håvard Lieng
09de41c0a2 Use ErrorMessage component 2018-10-06 08:46:28 +02:00
Ken-Håvard Lieng
66bf957460 Update dependencies 2018-10-06 08:09:29 +02:00
Ken-Håvard Lieng
ccdd56fea4 Explicitly set input background color 2018-09-24 01:10:21 +02:00
Ken-Håvard Lieng
963e36c296 Preload fonts 2018-09-18 22:09:08 +02:00
Ken-Håvard Lieng
1de1d1473d Drop go 1.8 support 2018-08-31 04:09:07 +02:00
Ken-Håvard Lieng
47bc78b80a Update all dependencies 2018-08-31 03:57:19 +02:00
Ken-Håvard Lieng
628dc66685 Go modules! 2018-08-31 03:08:17 +02:00
Ken-Håvard Lieng
b0b3489e15 Update go version on travis 2018-08-23 22:03:48 +02:00
Ken-Håvard Lieng
5defd315f1
Merge pull request #33 from daftaupe/#17
Change Connect button to Add Network
2018-08-23 12:27:49 +02:00
Pierre-Alain TORET
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
Ken-Håvard Lieng
0b49df6bcf
Merge pull request #32 from daftaupe/#31
Add command line option for server binding
2018-08-22 15:53:34 +02:00
Pierre-Alain TORET
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
Ken-Håvard Lieng
508969e189 Update client dependencies 2018-08-22 00:53:45 +02:00
Ken-Håvard Lieng
3dea4d6513 Add go 1.11rc1 travis build 2018-08-22 00:36:28 +02:00
Ken-Håvard Lieng
c8c09bce8c Add option to choose which address to listen on, closes #31 2018-08-22 00:31:29 +02:00
Ken-Håvard Lieng
004e7890e5 Update client dependencies 2018-08-12 23:28:58 +02:00
Ken-Håvard Lieng
f20ca4038e Fix connect form readonly casing 2018-08-10 21:35:37 +02:00
Ken-Håvard Lieng
1406b87d77 Fix checkbox 2018-08-10 21:30:44 +02:00
Ken-Håvard Lieng
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
Ken-Håvard Lieng
e2c6cedc27
Merge pull request #30 from daftaupe/#26
Add support for X-Forwarded-For
2018-07-25 00:18:29 +02:00
Pierre-Alain TORET
8ed27bf54b Add support for X-Forwarded-For 2018-07-24 22:01:01 +02:00
Ken-Håvard Lieng
a4d2cf17aa Hide original checkbox better 2018-06-20 17:31:59 +02:00
Ken-Håvard Lieng
fb287dce2f Fix tests 2018-06-18 16:12:19 +02:00
Ken-Håvard Lieng
352f7a8487
Merge pull request #23 from EdwardBetts/spelling
Correct spelling mistakes.
2018-06-18 15:59:17 +02:00
Edward Betts
ad238726b7 Correct spelling mistakes. 2018-06-18 14:47:51 +01:00
Ken-Håvard Lieng
8f20593b26 Create root directory explicitly, closes #22 2018-06-17 23:47:47 +02:00
Ken-Håvard Lieng
fde6a9e630 Wait 15 seconds before reconnecting if the connection closed before registration finished 2018-06-17 22:53:22 +02:00
Ken-Håvard Lieng
9669092148 Fix horizontal overflow 2018-06-10 21:35:12 +02:00
Ken-Håvard Lieng
3d2dbd5527 Add custom checkbox 2018-06-10 21:25:58 +02:00
Ken-Håvard Lieng
b07d1eb871 Update client dependencies 2018-06-07 23:12:09 +02:00
Ken-Håvard Lieng
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
Ken-Håvard Lieng
f5de115534 Remove TTF fonts 2018-06-01 22:10:20 +02:00
Ken-Håvard Lieng
494dbc4cf5 Remove session expiration timer 2018-06-01 05:59:13 +02:00
Ken-Håvard Lieng
c49bbc72d4 Do all session pruning in a single goroutine 2018-06-01 05:40:12 +02:00
Ken-Håvard Lieng
e8f5809940 Do session disk writes in a new goroutine 2018-06-01 04:47:11 +02:00
Ken-Håvard Lieng
e0200a2b2a Name all storage interface params, return slices of pointers 2018-06-01 04:16:38 +02:00
Ken-Håvard Lieng
09248edd59 Fix irc handler tests 2018-06-01 03:37:22 +02:00
Ken-Håvard Lieng
24f9553aa5 Persist, renew and delete sessions, refactor storage package, move reusable packages to pkg 2018-05-31 23:24:59 +02:00
Ken-Håvard Lieng
121582f72a Update client dependencies 2018-05-31 23:23:01 +02:00
Ken-Håvard Lieng
70322c2e43
Add Sauce Labs credit 2018-05-30 04:42:32 +02:00
Ken-Håvard Lieng
9529af55c7 Update prettier to 1.13.0 2018-05-28 03:16:05 +02:00
Ken-Håvard Lieng
21b6740e8b Update client dependencies 2018-05-26 00:04:11 +02:00
Ken-Håvard Lieng
09d57b7023 Use easyjson 2018-05-25 23:54:36 +02:00
Ken-Håvard Lieng
e7cff1686e Clean up some things 2018-05-25 04:12:02 +02:00
Ken-Håvard Lieng
e2a895a1b9 Autoprefix css in development 2018-05-25 03:27:53 +02:00
Ken-Håvard Lieng
b4c9338772 Change browserslist 2018-05-25 03:26:41 +02:00
Ken-Håvard Lieng
637f0d956b Wait until a websocket connection comes in before creating new anonymous sessions 2018-05-22 03:57:52 +02:00
Ken-Håvard Lieng
27653982d7
Delete docker.sh 2018-05-19 01:02:50 +02:00
Ken-Håvard Lieng
2f2c500453 Use correct ssl property name, closes #14 2018-05-18 05:33:33 +02:00
Ken-Håvard Lieng
d27d108a07 Make sure the connect form port is always a string 2018-05-18 05:13:25 +02:00
Ken-Håvard Lieng
4ac0dd7c4b Handle default port properly, closes #18 2018-05-18 04:15:20 +02:00
Ken-Håvard Lieng
b09da1fc3b
Merge pull request #16 from prologic/consistency_config_options
Makes configuration options consistent
2018-05-18 03:50:31 +02:00
Ken-Håvard Lieng
2ada552220 Validate port numbers better 2018-05-18 03:39:40 +02:00
James Mills
16ce3cdfa5
Make configuration options consistent 2018-05-17 18:37:33 -07:00
Ken-Håvard Lieng
9806d6c12f Use nick as username and realname if they are missing 2018-05-18 03:14:22 +02:00
Ken-Håvard Lieng
8f8adc37e7 Update react-virtualized to 9.19.0 2018-05-18 02:38:58 +02:00
Ken-Håvard Lieng
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
James Mills
276d8f7849
Improved Dockerfile to properly build and ship a runtime image 2018-05-17 15:44:15 -07:00
Ken-Håvard Lieng
6fd5235ec9 Add new connect form, closes #7 2018-05-16 05:02:48 +02:00
Ken-Håvard Lieng
f502fea5c1 Update client dependencies 2018-05-16 05:01:31 +02:00
Ken-Håvard Lieng
abc495f849 Update README 2018-05-16 03:54:19 +02:00
Ken-Håvard Lieng
4fafe2b158 Update gulp to 4.0.0 2018-05-16 03:46:42 +02:00
Ken-Håvard Lieng
29a225ed13 Make it run better in IE11 2018-05-06 21:36:05 +02:00
Ken-Håvard Lieng
91e5556c86 Make it run in IE11 2018-05-05 21:54:00 +02:00
Ken-Håvard Lieng
de36fe682a Update server dependencies 2018-05-04 23:39:27 +02:00
Ken-Håvard Lieng
fb8fec38ff Use correct hash length when reading the push cookie 2018-04-30 22:53:29 +02:00
Ken-Håvard Lieng
d4d03eac12 Add promise polyfill 2018-04-30 22:41:12 +02:00
Ken-Håvard Lieng
33e0f67766 Add IRCv3 tag parsing 2018-04-29 03:49:02 +02:00
Ken-Håvard Lieng
62e115498f Deal with empty ISUPPORT param names 2018-04-29 02:13:22 +02:00
Ken-Håvard Lieng
f2504cc245 Add RPL_ISUPPORT parsing 2018-04-28 20:31:44 +02:00
Ken-Håvard Lieng
735f96d3b1 Remove unused eslint rule 2018-04-27 03:14:35 +02:00
Ken-Håvard Lieng
f72253966b Throw more test cases at the message parser, fix edge case 2018-04-27 02:56:35 +02:00
Ken-Håvard Lieng
b4bdcd4939 Update README 2018-04-26 21:37:58 +02:00
Ken-Håvard Lieng
0648b67cb8 Use random session IDs instead of jwt 2018-04-26 21:32:21 +02:00
Ken-Håvard Lieng
6f0ea05f4b Use shorter asset hashes 2018-04-26 21:19:47 +02:00
Ken-Håvard Lieng
1b202e7c2b Make sure the cookie stored channel exists on the correct server 2018-04-26 20:25:41 +02:00
Ken-Håvard Lieng
e132c8201f Use node 10.0.0 on travis 2018-04-26 19:57:39 +02:00
Ken-Håvard Lieng
4f72e164d7 Use immer 2018-04-25 05:52:55 +02:00
Ken-Håvard Lieng
7f755d2a83 Actually make sure the user is in the channel before embedding channel data 2018-04-24 21:21:42 +02:00
Ken-Håvard Lieng
8724121552 Update redux to 4.0.0 2018-04-17 21:53:41 +02:00
Ken-Håvard Lieng
0ebd2e5c38 Update client dependencies 2018-04-17 21:22:10 +02:00
Ken-Håvard Lieng
0941ed8549 Add reset-config flag 2018-04-15 01:25:21 +02:00
Ken-Håvard Lieng
39641c315f Add connect defaults readonly flag, closes #10 2018-04-15 01:02:28 +02:00
Ken-Håvard Lieng
fcd204321a Fix css bundle name 2018-04-15 00:58:51 +02:00
Ken-Håvard Lieng
d08bd43ba0 Hot reload server config 2018-04-15 00:57:11 +02:00
Ken-Håvard Lieng
60190fbd98 Update prettier to 1.12 2018-04-13 20:58:45 +02:00
Ken-Håvard Lieng
6ccc57ad64 Update gulp compress glob 2018-04-13 20:51:42 +02:00
Ken-Håvard Lieng
94f3777f5f Handle css with webpack 2018-04-13 20:47:39 +02:00
Ken-Håvard Lieng
3d4c1baeda Remove redundant eslint rules 2018-04-06 01:53:11 +02:00
Ken-Håvard Lieng
b176b79144 Add prettier 2018-04-06 01:46:22 +02:00
Ken-Håvard Lieng
0cbbc1b8ff Update client deps: react 16.3, babel 7 2018-04-05 21:16:37 +02:00
Ken-Håvard Lieng
1ae7d867a9 Use node 8.10.0 on travis 2018-03-25 01:51:54 +01:00
Ken-Håvard Lieng
87d7337d21 Update .travis.yml 2018-03-25 01:47:08 +01:00
Ken-Håvard Lieng
19bcc51eb4 Update client dependencies 2018-03-25 01:34:41 +01:00
Ken-Håvard Lieng
20c3855ced Add go 1.10 travis build 2018-02-19 00:01:48 +01:00
2039 changed files with 368592 additions and 130685 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.9
- 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 --lts
- nvm use --lts
- npm install -g yarn
- npm install -g gulp
- yarn global add gulp-cli
- 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.*

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"javascript.preferences.importModuleSpecifier": "non-relative"
}

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

@ -1,91 +1,126 @@
# dispatch [![Build Status](https://travis-ci.org/khlieng/dispatch.svg?branch=master)](https://travis-ci.org/khlieng/dispatch)
# dispatch [![Build Status](https://travis-ci.com/khlieng/dispatch.svg?branch=master)](https://travis-ci.com/khlieng/dispatch)
#### [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
- Single binary with no dependencies
- DCC downloads
- SASL
- 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.11 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
docker run \
-p <http port>:80 \
-p <https port>:443 \
-v <path>:/data \
--restart unless-stopped \
-d khlieng/dispatch
```
## 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
```
## IRC Channel
#dispatch @ irc.libera.chat
## 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,35 @@
{
"extends": "airbnb",
"extends": ["airbnb", "prettier", "prettier/react"],
"parser": "babel-eslint",
"env": {
"browser": true
},
"plugins": ["babel"],
"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,
"no-unused-expressions": 0,
"babel/no-unused-expressions": 2
},
"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');
}

1198
client/css/style.css Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,118 +1,116 @@
var path = require('path');
var exec = require('child_process').exec;
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) {
if (err) throw new gutil.PluginError('webpack', err);
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);
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 +120,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,16 +1,20 @@
import { COMMAND } from 'state/actions';
import { join, part, invite, kick, setTopic } from 'state/channels';
import { sendMessage, raw } from 'state/messages';
import { setNick, disconnect, whois, away } from 'state/servers';
import { setNick, disconnect, whois, away } from 'state/networks';
import { openPrivateChat } from 'state/privateChats';
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',
'/part [channel] - Leave the current or specified channel',
'/nick <nick> - Change nick',
'/quit - Disconnect from the current server',
'/quit - Disconnect from the current network',
'/me <message> - Send action message',
'/topic [topic] - Show or set topic in the current channel',
'/msg <target> <message> - Send message to the specified channel or user',
@ -19,151 +23,153 @@ const help = [
'/kick <nick> - Kick user from the current channel',
'/whois <nick> - Get information about user',
'/away [message] - Set or clear away message',
'/raw [message] - Send raw IRC message to the current server',
'/raw [message] - Send raw IRC message to the current network',
'/help [command]... - Print help for all or the specified command(s)'
];
const text = content => ({ content });
const error = content => ({ content, type: 'error' });
const prompt = content => ({ content, type: 'prompt' });
const findHelp = cmd => find(help, line => line.slice(1, line.indexOf(' ')) === cmd);
const findHelp = cmd =>
find(help, line => line.slice(1, line.indexOf(' ')) === cmd);
export default createCommandMiddleware(COMMAND, {
join({ dispatch, server }, channel) {
join({ dispatch, network }, channel) {
if (channel) {
if (channel[0] !== '#') {
return error('Bad channel name');
}
dispatch(join([channel], server));
dispatch(select(server, channel));
dispatch(join([channel], network));
} else {
return error('Missing channel');
}
},
part({ dispatch, server, channel, isChannel }, partChannel) {
part({ dispatch, network, channel, inChannel }, partChannel) {
if (partChannel) {
dispatch(part([partChannel], server));
} else if (isChannel) {
dispatch(part([channel], server));
dispatch(part([partChannel], network));
} else if (inChannel) {
dispatch(part([channel], network));
} else {
return error('This is not a channel');
}
},
nick({ dispatch, server }, nick) {
nick({ dispatch, network }, nick) {
if (nick) {
dispatch(setNick(nick, server));
dispatch(setNick(nick, network));
} else {
return error('Missing nick');
}
},
quit({ dispatch, server }) {
dispatch(disconnect(server));
quit({ dispatch, network }) {
dispatch(disconnect(network));
},
me({ dispatch, server, channel }, ...message) {
me({ dispatch, network, channel }, ...message) {
const msg = message.join(' ');
if (msg !== '') {
dispatch(sendMessage(`\x01ACTION ${msg}\x01`, channel, server));
dispatch(sendMessage(`\x01ACTION ${msg}\x01`, channel, network));
} else {
return error('Messages can not be empty');
}
},
topic({ dispatch, getState, server, channel }, ...newTopic) {
topic({ dispatch, getState, network, channel }, ...newTopic) {
if (newTopic.length > 0) {
dispatch(setTopic(newTopic.join(' '), channel, server));
} else {
const topic = getState().channels.getIn([server, channel, 'topic']);
dispatch(setTopic(newTopic.join(' '), channel, network));
return;
}
if (channel) {
const { topic } = getState().channels[network][channel];
if (topic) {
return text(topic);
}
return 'No topic set';
}
return 'No topic set';
},
msg({ dispatch, server }, target, ...message) {
msg({ dispatch, network }, target, ...message) {
if (!target) {
return error('Missing nick/channel');
}
const msg = message.join(' ');
if (msg !== '') {
dispatch(sendMessage(message.join(' '), target, server));
dispatch(select(server, target));
dispatch(sendMessage(message.join(' '), target, network));
if (!isChannel(target)) {
dispatch(openPrivateChat(network, target));
}
dispatch(select(network, target));
} else {
return error('Messages can not be empty');
}
},
say({ dispatch, server, channel }, ...message) {
say({ dispatch, network, channel }, ...message) {
if (!channel) {
return error('Messages can only be sent to channels or users');
}
const msg = message.join(' ');
if (msg !== '') {
dispatch(sendMessage(message.join(' '), channel, server));
dispatch(sendMessage(message.join(' '), channel, network));
} else {
return error('Messages can not be empty');
}
},
invite({ dispatch, server, channel, isChannel }, user, inviteChannel) {
if (!inviteChannel && !isChannel) {
invite({ dispatch, network, channel, inChannel }, user, inviteChannel) {
if (!inviteChannel && !inChannel) {
return error('This is not a channel');
}
if (user && inviteChannel) {
dispatch(invite(user, inviteChannel, server));
dispatch(invite(user, inviteChannel, network));
} else if (user && channel) {
dispatch(invite(user, channel, server));
dispatch(invite(user, channel, network));
} else {
return error('Missing nick');
}
},
kick({ dispatch, server, channel, isChannel }, user) {
if (!isChannel) {
kick({ dispatch, network, channel, inChannel }, user) {
if (!inChannel) {
return error('This is not a channel');
}
if (user) {
dispatch(kick(user, channel, server));
dispatch(kick(user, channel, network));
} else {
return error('Missing nick');
}
},
whois({ dispatch, server }, user) {
whois({ dispatch, network }, user) {
if (user) {
dispatch(whois(user, server));
dispatch(whois(user, network));
} else {
return error('Missing nick');
}
},
away({ dispatch, server }, ...message) {
away({ dispatch, network }, ...message) {
const msg = message.join(' ');
dispatch(away(msg, server));
dispatch(away(msg, network));
if (msg !== '') {
return 'Away message set';
}
return 'Away message cleared';
},
raw({ dispatch, server }, ...message) {
raw({ dispatch, network }, ...message) {
if (message.length > 0 && message[0] !== '') {
const cmd = `${message[0].toUpperCase()} ${message.slice(1).join(' ')}`;
dispatch(raw(cmd, server));
dispatch(raw(cmd, network));
return prompt(`=> ${cmd}`);
}
return [
prompt('=> /raw'),
error('Missing message')
];
return [prompt('=> /raw'), error('Missing message')];
},
help(_, ...commands) {
@ -184,9 +190,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,95 @@
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(/* webpackChunkName: "connect" */ 'containers/Connect')
);
const Settings = lazy(() => import('containers/Settings'));
const App = ({
connected,
tab,
channels,
networks,
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}
networks={networks}
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,132 @@
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 = (network, target) => this.props.select(network, target);
handleConnectClick = () => this.props.push('/connect');
handleSettingsClick = () => this.props.push('/settings');
render() {
const {
tab,
channels,
networks,
privateChats,
showTabList,
openModal
} = this.props;
const tabs = [];
const className = classnames('tablist', {
'off-canvas': showTabList
});
channels.forEach(network => {
const { address } = network;
const srv = networks[address];
tabs.push(
<TabListItem
key={address}
network={address}
content={srv.name}
selected={tab.network === address && !tab.name}
connected={srv.connected}
onClick={this.handleTabClick}
/>
);
const chanCount = count(network.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 tab-label-channels"
onClick={() => openModal('channel', address)}
>
<span>CHANNELS {chanLabel}</span>
<Button title="Join Channel">+</Button>
</div>
);
network.channels.forEach(({ name, joined }) =>
tabs.push(
<TabListItem
key={address + name}
network={address}
target={name}
content={name}
joined={joined}
selected={tab.network === 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}
network={address}
target={nick}
content={nick}
selected={tab.network === address && tab.name === nick}
onClick={this.handleTabClick}
/>
)
);
}
});
return (
<div className={className}>
<div className="tab-container">{tabs}</div>
<div className="side-buttons">
<Button
icon={FiPlus}
aria-label="Connect"
onClick={this.handleConnectClick}
/>
<Button icon={FiUser} aria-label="User" />
<Button
icon={FiSettings}
aria-label="Settings"
onClick={this.handleSettingsClick}
/>
</div>
</div>
);
}
}

View File

@ -0,0 +1,46 @@
import React from 'react';
import classnames from 'classnames';
function splitContent(content) {
let start = 0;
while (content[start] === '#') {
start++;
}
if (start > 0) {
return [content.slice(0, start), content.slice(start)];
}
return [null, content];
}
const TabListItem = ({
target,
content,
network,
selected,
connected,
joined,
error,
onClick
}) => {
const className = classnames({
'tab-network': !target,
success: !target && connected,
error: (!target && !connected) || (!joined && error),
disabled: !!target && !error && joined === false,
selected
});
const [prefix, name] = splitContent(content);
return (
<p className={className} onClick={() => onClick(network, target)}>
<span className="tab-content">
{prefix && <span className="tab-prefix">{prefix}</span>}
{name}
</span>
</p>
);
};
export default TabListItem;

View File

@ -0,0 +1,72 @@
import React from 'react';
import stringToRGB from 'utils/color';
function nickStyle(nick, color) {
const style = {
fontWeight: 400
};
if (color) {
style.color = stringToRGB(nick);
}
return style;
}
function renderBlock(block, coloredNick, key) {
switch (block.type) {
case 'text':
return block.text;
case 'link':
return (
<a target="_blank" rel="noopener noreferrer" href={block.url} key={key}>
{block.text}
</a>
);
case 'format':
return (
<span style={block.style} key={key}>
{block.text}
</span>
);
case 'nick':
return (
<span
className="message-sender"
style={nickStyle(block.text, coloredNick)}
key={key}
>
{block.text}
</span>
);
case 'events':
return (
<span className="message-events-more" key={key}>
{block.text}
</span>
);
default:
return null;
}
}
const Text = ({ children, coloredNick }) => {
if (!children) {
return null;
}
if (children.length > 1) {
let key = 0;
return children.map(block => renderBlock(block, coloredNick, key++));
}
if (children.length === 1) {
return renderBlock(children[0], coloredNick);
}
return children;
};
export default Text;

View File

@ -0,0 +1,155 @@
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 Text from 'components/Text';
import useModal from 'components/modals/useModal';
import Button from 'components/ui/Button';
import { join } from 'state/channels';
import { searchChannels } from 'state/channelSearch';
import { linkify } from 'utils';
import colorify from 'utils/colorify';
const Channel = memo(({ network, name, topic, userCount, joined }) => {
const dispatch = useDispatch();
const handleClick = () => dispatch(join([name], network));
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">
<Text>{colorify(linkify(topic))}</Text>
</p>
</div>
);
});
const AddChannel = () => {
const [modal, network, 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(network, ''));
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(network, 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], network));
}
}
};
const handleLoadMore = () =>
dispatch(searchChannels(network, 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={`${network} ${channel.name}`}
network={network}
joined={channels[network]?.[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,30 @@
import React from 'react';
import Modal from 'react-modal';
import { useSelector } from 'react-redux';
import { FiX } from 'react-icons/fi';
import Text from 'components/Text';
import Button from 'components/ui/Button';
import useModal from 'components/modals/useModal';
import { getSelectedChannel } from 'state/channels';
import { linkify } from 'utils';
import colorify from 'utils/colorify';
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">
<Text>{colorify(linkify(topic))}</Text>
</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,53 +10,54 @@ export default class Chat extends Component {
handleCloseClick = () => {
const { tab, part, closePrivateChat, disconnect } = this.props;
if (tab.isChannel()) {
part([tab.name], tab.server);
if (isChannel(tab)) {
part([tab.name], tab.network);
} else if (tab.name) {
closePrivateChat(tab.server, tab.name);
closePrivateChat(tab.network, tab.name);
} else {
disconnect(tab.server);
disconnect(tab.network);
}
};
handleSearch = phrase => {
const { tab, searchMessages } = this.props;
if (tab.isChannel()) {
searchMessages(tab.server, tab.name, phrase);
if (isChannel(tab)) {
searchMessages(tab.network, tab.name, phrase);
}
};
handleNickClick = nick => {
const { tab, openPrivateChat, select } = this.props;
openPrivateChat(tab.server, nick);
select(tab.server, nick);
openPrivateChat(tab.network, nick);
select(tab.network, nick);
};
handleTitleChange = title => {
const { setServerName, tab } = this.props;
setServerName(title, tab.server);
const { setNetworkName, tab } = this.props;
setNetworkName(title, tab.network);
};
handleNickChange = nick => {
const { setNick, tab } = this.props;
setNick(nick, tab.server, true);
setNick(nick, tab.network, true);
};
handleNickEditDone = nick => {
const { setNick, tab } = this.props;
setNick(nick, tab.server);
setNick(nick, tab.network);
};
render() {
const {
channel,
coloredNicks,
currentInputHistoryEntry,
hasMoreMessages,
messages,
nick,
search,
showUserList,
status,
error,
tab,
title,
users,
@ -63,41 +65,41 @@ 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';
} else {
chatClass = 'chat-server';
chatClass = 'chat-network';
}
return (
<div className={chatClass}>
<ChatTitle
channel={channel}
status={status}
error={error}
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}
@ -113,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,87 @@
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 { isValidNetworkName } from 'state/networks';
import { isChannel } from 'utils';
const ChatTitle = ({
error,
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 networkError = null;
if (!tab.name && error) {
networkError = <span className="chat-topic error">Error: {error}</span>;
}
return (
<div>
<div className="chat-title-bar">
<Navicon />
<Editable
className="chat-title"
editable={!tab.name}
value={title}
validate={isValidNetworkName}
onChange={onTitleChange}
>
<span className="chat-title">{title}</span>
</Editable>
<div className="chat-topic-wrap">
{channel?.topic && (
<span
className="chat-topic"
onClick={() => openModal('topic', channel.name)}
>
{channel.topic}
</span>
)}
{networkError}
</div>
{tab.name && (
<Button
icon={FiSearch}
title="Search"
aria-label="Search"
onClick={onToggleSearch}
/>
)}
<Button
icon={FiX}
title={closeTitle}
aria-label={closeTitle}
onClick={onCloseClick}
/>
<Button
icon={FiUsers}
className="button-userlist"
aria-label="Users"
onClick={onToggleUserList}
/>
</div>
<div className="userlist-bar">
<FiUsers />
{channel?.users.length}
</div>
</div>
);
};
export default memo(ChatTitle);

View File

@ -0,0 +1,50 @@
import React, { memo } from 'react';
import classnames from 'classnames';
import Text from 'components/Text';
import stringToRGB from 'utils/color';
const Message = ({ message, coloredNick, onNickClick }) => {
const className = classnames('message', {
[`message-${message.type}`]: message.type
});
if (message.type === 'date') {
return (
<div className={className}>
{message.content}
<hr />
</div>
);
}
const style = {
paddingLeft: `${message.indent + 15}px`,
textIndent: `-${message.indent}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>
{' '}
<Text coloredNick={coloredNick}>{message.content}</Text>
</span>
</p>
);
};
export default memo(Message);

View File

@ -0,0 +1,306 @@
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.network, 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.network}:${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.network, 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 (
<div style={style}>
<Message
message={message}
coloredNick={coloredNicks}
onNickClick={onNickClick}
/>
</div>
);
};
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.network);
} else if (tab.name) {
onMessage(e.target.value, tab.name, tab.network);
}
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,28 @@
import React, { memo } from 'react';
import Text from 'components/Text';
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>
{' '}
<Text>{linkify(result.content)}</Text>
</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,247 @@
import React, { Component } from 'react';
import { createSelector } from 'reselect';
import { Form, withFormik } from 'formik';
import { FiMoreHorizontal } from 'react-icons/fi';
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';
const getSortedDefaultChannels = createSelector(
defaults => defaults.channels,
channels => channels.split(',').sort()
);
const 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;
};
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 className="connect-section">
<h2>SASL</h2>
<TextInput name="account" />
<TextInput name="password" type="password" noTrim />
</div>
{!hexIP && <TextInput name="username" />}
<TextInput
name="serverPassword"
label="Server Password"
type="password"
noTrim
/>
<TextInput name="realname" noTrim />
</>
);
};
transformPort = port => {
if (!port) {
return this.props.values.tls ? '6697' : '6667';
}
return port;
};
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
classNameLabel="connect-form-ssl"
name="tls"
label="SSL"
topLabel
onChange={this.handleSSLChange}
/>
</div>
<Error name="host" />
<Error name="port" />
<TextInput name="nick" />
<TextInput name="channels" transform={transformChannels} />
{this.state.showOptionals && this.renderOptionals()}
<Button
className="connect-form-button-optionals"
icon={FiMoreHorizontal}
aria-label="Show more"
onClick={this.handleShowClick}
/>
<Button type="submit">Connect</Button>
</Form>
);
}
return (
<div className="connect">
<Navicon />
{form}
</div>
);
}
}
export default withFormik({
enableReinitialize: true,
mapPropsToValues: ({ defaults, query }) => {
let port = '6667';
if (query.port || defaults.port) {
port = query.port || defaults.port;
} else if (defaults.ssl) {
port = '6697';
}
let { channels } = query;
if (channels) {
channels = transformChannels(channels);
}
let ssl;
if (query.ssl === 'true') {
ssl = true;
} else if (query.ssl === 'false') {
ssl = false;
} else {
ssl = defaults.ssl || false;
}
return {
name: query.name || defaults.name,
host: query.host || defaults.host,
port,
nick: query.nick || localStorage.lastNick || '',
channels: channels || defaults.channels.join(','),
account: '',
password: '',
username: query.username || '',
serverPassword: defaults.serverPassword ? ' ' : '',
realname: query.realname || localStorage.lastRealname || '',
tls: ssl
};
},
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, false);
}
localStorage.lastNick = values.nick;
if (values.realname) {
localStorage.lastRealname = values.realname;
}
}
})(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, classNameLabel, ...props }) => (
<label
className={classnames('checkbox', classNameLabel, {
'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,128 @@
import React, { PureComponent } from 'react';
import { FastField } from 'formik';
import classnames from 'classnames';
import capitalize from 'lodash/capitalize';
import Error from 'components/ui/formik/Error';
export default class TextInput extends PureComponent {
constructor(props) {
super(props);
this.input = React.createRef();
window.addEventListener('resize', this.handleResize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}
handleResize = () => {
if (this.scroll) {
this.scroll = false;
this.scrollIntoView();
}
};
handleFocus = () => {
this.scroll = true;
setTimeout(() => {
this.scroll = false;
}, 2000);
};
scrollIntoView = () => {
if (this.input.current.scrollIntoViewIfNeeded) {
this.input.current.scrollIntoViewIfNeeded();
} else {
this.input.current.scrollIntoView();
}
};
render() {
const {
name,
label = capitalize(name),
noError,
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}
id={name}
autoCapitalize="off"
autoCorrect="off"
autoComplete="off"
spellCheck="false"
ref={this.input}
onFocus={this.handleFocus}
{...field}
{...props}
onChange={e => {
let v = e.target.value;
if (!noTrim) {
v = v.trim();
}
if (transform) {
v = transform(v);
}
if (v !== field.value) {
form.setFieldValue(name, v);
if (props.onChange) {
props.onChange(e);
}
}
}}
onBlur={e => {
field.onBlur(e);
if (props.onBlur) {
props.onBlur(e);
}
if (blurTransform) {
const v = blurTransform(e.target.value);
if (v && v !== field.value) {
form.setFieldValue(name, v);
}
}
}}
/>
<label
htmlFor={name}
className={classnames('textinput-label', 'textinput-1', {
value: field.value,
error: form.touched[name] && form.errors[name]
})}
>
{label}
</label>
<span
className={classnames('textinput-label', '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 { getServers } from 'state/servers';
import { openModal, getHasOpenModals } from 'state/modals';
import { getPrivateChats } from 'state/privateChats';
import { getNetworks } from 'state/networks';
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,
servers: getServers,
privateChats: getPrivateChats,
networks: getNetworks,
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,
getCurrentNetworkError,
disconnect,
setNick,
setNetworkName
} from 'state/networks';
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,
error: getCurrentNetworkError,
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,
setNetworkName,
toggleSearch,
toggleUserList
},
dispatch
),
inputActions: bindActionCreators(
{
add: addInputHistory,
reset: resetInputHistory,
increment: incrementInputHistory,
decrement: decrementInputHistory
},
dispatch
)
});
export default connect(mapState, mapDispatch)(Chat);

View File

@ -1,18 +1,20 @@
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 { connect as connectNetwork } from 'state/networks';
import { select } from 'state/tab';
import connect from 'utils/connect';
const mapState = createStructuredSelector({
defaults: getConnectDefaults
defaults: getConnectDefaults,
hexIP: state => getApp(state).hexIP,
query: state => state.router.query
});
const mapDispatch = {
join,
connect: connectServer,
connect: connectNetwork,
select
};

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, { network, target }) => {
const messages = get(state, ['messages', network, 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,25 +1,30 @@
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) };
function createContext({ dispatch, getState }, { network, channel }) {
return {
dispatch,
getState,
network,
channel,
inChannel: isChannel(channel)
};
}
// TODO: Pull this out as convenience action
function process({ dispatch, server, channel }, result) {
function process({ dispatch, network, channel }, result) {
if (typeof result === 'string') {
dispatch(inform(result, server, channel));
dispatch(inform(result, network, channel));
} else if (Array.isArray(result)) {
if (typeof result[0] === 'string') {
dispatch(inform(result, server, channel));
dispatch(inform(result, network, channel));
} else if (typeof result[0] === 'object') {
dispatch(addMessages(result, server, channel));
dispatch(addMessages(result, network, channel));
}
} else if (typeof result === 'object' && result) {
dispatch(print(result.content, server, channel, result.type));
dispatch(print(result.content, network, channel, result.type));
}
}
@ -27,7 +32,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

@ -10,7 +10,7 @@ const message = store => next => {
return action => {
if (action.type === ADD_MESSAGES && action.prepend) {
const key = `${action.server} ${action.channel}`;
const key = `${action.network} ${action.channel}`;
if (ready[key]) {
ready[key] = false;
@ -19,7 +19,7 @@ const message = store => next => {
cache[key] = action;
} else if (action.type === ADD_FETCHED_MESSAGES) {
const key = `${action.server} ${action.channel}`;
const key = `${action.network} ${action.channel}`;
ready[key] = true;
if (cache[key]) {

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

@ -0,0 +1,27 @@
import capitalize from 'lodash/capitalize';
import { getRouter } from 'state';
import { getCurrentNetworkName } from 'state/networks';
import { observe } from 'utils/observe';
export default function documentTitle({ store }) {
observe(store, [getRouter, getCurrentNetworkName], (router, networkName) => {
let title;
if (router.route === 'chat') {
const { network, name } = router.params;
if (name) {
title = `${name} @ ${networkName || network}`;
} else {
title = networkName || network;
}
} else {
title = capitalize(router.route);
}
if (title) {
document.title = `${title} | Dispatch`;
} else {
document.title = 'Dispatch';
}
});
}

View File

@ -0,0 +1,15 @@
import { setCharWidth } from 'state/app';
import { stringWidth } from 'utils';
export default async function fonts({ store }) {
let { charWidth } = localStorage;
if (charWidth) {
store.dispatch(setCharWidth(parseFloat(charWidth)));
} else {
await document.fonts.load('16px Roboto Mono');
charWidth = stringWidth(' ', '16px Roboto Mono');
store.dispatch(setCharWidth(charWidth));
localStorage.charWidth = 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,47 @@
import { INIT } from 'state/actions';
import { getConnected, getWrapWidth } from 'state/app';
import { searchChannels } from 'state/channelSearch';
import { addMessages } from 'state/messages';
import { when } from 'utils/observe';
function loadState({ store }, env) {
store.dispatch({
type: INIT,
settings: env.settings,
networks: env.networks,
channels: env.channels,
openDMs: env.openDMs,
users: env.users,
app: {
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, network, to, next } = env.messages;
store.dispatch(addMessages(messages, network, to, false, next));
});
}
if (env.networks) {
when(store, getConnected, () =>
// Cache top channels for each network
env.networks.forEach(({ host }) =>
store.dispatch(searchChannels(host, ''))
)
);
}
}
/* 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;
}
}
)
);
}

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

@ -0,0 +1,196 @@
import { socketAction } from 'state/actions';
import { kicked } from 'state/channels';
import {
print,
addMessage,
addMessages,
addEvent,
broadcastEvent
} from 'state/messages';
import { openModal } from 'state/modals';
import { reconnect } from 'state/networks';
import { select } from 'state/tab';
import { find } from 'utils';
function findChannels(state, network, user) {
const channels = [];
Object.keys(state.channels[network]).forEach(channel => {
if (find(state.channels[network][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.network, message.to));
return false;
},
pm(message) {
dispatch(addMessage(message, message.network, message.from));
return false;
},
messages({ messages, network, to, prepend, next }) {
dispatch(addMessages(messages, network, to, prepend, next));
return false;
},
join({ user, network, channels }) {
dispatch(addEvent(network, channels[0], 'join', user));
},
part({ user, network, channel, reason }) {
dispatch(addEvent(network, channel, 'part', user, reason));
},
quit({ user, network, reason }) {
const channels = findChannels(getState(), network, user);
dispatch(broadcastEvent(network, channels, 'quit', user, reason));
},
kick({ network, channel, sender, user, reason }) {
dispatch(kicked(network, channel, user));
dispatch(addEvent(network, channel, 'kick', user, sender, reason));
},
nick({ network, oldNick, newNick }) {
if (oldNick) {
const channels = findChannels(getState(), network, oldNick);
dispatch(broadcastEvent(network, channels, 'nick', oldNick, newNick));
}
},
topic({ network, channel, topic, nick }) {
if (nick) {
dispatch(addEvent(network, channel, 'topic', nick, topic));
}
},
motd({ content, network }) {
dispatch(
addMessages(
content.map(line => ({ content: line })),
network
)
);
return false;
},
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.network,
tab.name
)
);
return false;
},
print(message) {
const tab = getState().tab.selected;
dispatch(addMessage(message, tab.network, tab.name));
return false;
},
error({ network, target, message }) {
const state = getState();
const tab = state.tab.selected;
if (network === tab.network) {
// Print it in the current channel if the error happened on
// the current network
target = tab.name;
} else if (!state.channels[network]?.[target]) {
// Print it the network tab if the target does not exist
target = null;
}
dispatch(
addMessage({ content: message, type: 'error' }, network, target)
);
return false;
},
connection_update({ network, errorType }) {
if (errorType === 'verify') {
dispatch(
openModal('confirm', {
question:
'The network is using a self-signed certificate, continue anyway?',
onConfirm: () =>
dispatch(
reconnect(network, {
skipVerify: true
})
)
})
);
}
},
dcc_send({ network, from, filename, size, url }) {
const networkName = getState().networks[network]?.name || network;
dispatch(
openModal('confirm', {
question: `${from} on ${networkName} is sending you (${size}): ${filename}`,
confirmation: 'Download',
onConfirm: () => {
const a = document.createElement('a');
a.href = url;
a.click();
}
})
);
}
};
const afterHandlers = {
channel_forward(forward) {
const { selected } = getState().tab;
if (
selected.network === forward.network &&
selected.name === forward.old
) {
dispatch(select(forward.network, 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 (handlers[type]?.(data) === false) {
return;
}
dispatch(action);
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.network) {
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;
@ -9,12 +10,10 @@ const smallScreen = 600;
export default function widthUpdates({ store }) {
when(store, getCharWidth, charWidth => {
window.messageIndent = 6 * charWidth;
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 +25,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

@ -1,5 +1,5 @@
export default {
connect: '/connect',
settings: '/settings',
chat: '/:server(/:name)'
chat: '/:network(/:name)'
};

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

@ -0,0 +1,20 @@
import { connect, setNetworkName } from '../networks';
describe('setNetworkName()', () => {
it('passes valid names to the network', () => {
const name = 'cake';
const network = 'srv';
expect(setNetworkName(name, network)).toMatchObject({
socket: {
type: 'set_network_name',
data: { name, network }
}
});
});
it('does not pass invalid names to the network', () => {
expect(setNetworkName('', 'srv').socket).toBeUndefined();
expect(setNetworkName(' ', 'srv').socket).toBeUndefined();
});
});

View File

@ -0,0 +1,430 @@
import reducer, { compareUsers, getSortedChannels } from '../channels';
import { connect } from '../networks';
import * as actions from '../actions';
describe('channel reducer', () => {
it('removes channels on PART', () => {
let state = {
srv1: {
chan1: {},
chan2: {},
chan3: {}
},
srv2: {
chan1: {}
}
};
state = reducer(state, {
type: actions.PART,
network: 'srv1',
channels: ['chan1', 'chan3']
});
expect(state).toEqual({
srv1: {
chan2: {}
},
srv2: {
chan1: {}
}
});
});
it('handles SOCKET_PART', () => {
let state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
state = reducer(state, socket_join('srv', 'chan1', 'nick2'));
state = reducer(state, socket_join('srv', 'chan2', 'nick2'));
state = reducer(state, {
type: actions.socket.PART,
network: 'srv',
channel: 'chan1',
user: 'nick2'
});
expect(state).toEqual({
srv: {
chan1: {
name: 'chan1',
joined: true,
users: [{ mode: '', nick: 'nick1', renderName: 'nick1' }]
},
chan2: {
name: 'chan2',
joined: true,
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
}
}
});
});
it('handles SOCKET_JOIN', () => {
const state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
expect(state).toEqual({
srv: {
chan1: {
name: 'chan1',
joined: true,
users: [{ mode: '', nick: 'nick1', renderName: 'nick1' }]
}
}
});
});
it('handles SOCKET_QUIT', () => {
let state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
state = reducer(state, socket_join('srv', 'chan1', 'nick2'));
state = reducer(state, socket_join('srv', 'chan2', 'nick2'));
state = reducer(state, {
type: actions.socket.QUIT,
network: 'srv',
user: 'nick2'
});
expect(state).toEqual({
srv: {
chan1: {
name: 'chan1',
joined: true,
users: [{ mode: '', nick: 'nick1', renderName: 'nick1' }]
},
chan2: {
name: 'chan2',
joined: true,
users: []
}
}
});
});
it('handles KICKED', () => {
let state = reducer(
undefined,
connect({
host: 'srv',
nick: 'nick2'
})
);
state = reducer(state, socket_join('srv', 'chan1', 'nick1'));
state = reducer(state, socket_join('srv', 'chan1', 'nick2'));
state = reducer(state, socket_join('srv', 'chan2', 'nick2'));
state = reducer(state, {
type: actions.KICKED,
network: 'srv',
channel: 'chan2',
user: 'nick2',
self: true
});
expect(state).toEqual({
srv: {
chan1: {
name: 'chan1',
joined: true,
users: [
{ mode: '', nick: 'nick1', renderName: 'nick1' },
{ mode: '', nick: 'nick2', renderName: 'nick2' }
]
},
chan2: {
name: 'chan2',
joined: false,
users: []
}
}
});
state = reducer(state, {
type: actions.KICKED,
network: 'srv',
channel: 'chan1',
user: 'nick1'
});
expect(state).toEqual({
srv: {
chan1: {
name: 'chan1',
joined: true,
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
},
chan2: {
name: 'chan2',
joined: false,
users: []
}
}
});
});
it('handles SOCKET_NICK', () => {
let state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
state = reducer(state, socket_join('srv', 'chan1', 'nick2'));
state = reducer(state, socket_join('srv', 'chan2', 'nick2'));
state = reducer(state, {
type: actions.socket.NICK,
network: 'srv',
oldNick: 'nick1',
newNick: 'nick3'
});
expect(state).toEqual({
srv: {
chan1: {
name: 'chan1',
joined: true,
users: [
{ mode: '', nick: 'nick3', renderName: 'nick3' },
{ mode: '', nick: 'nick2', renderName: 'nick2' }
]
},
chan2: {
name: 'chan2',
joined: true,
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
}
}
});
});
it('handles SOCKET_USERS', () => {
let state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
state = reducer(state, {
type: actions.socket.USERS,
network: 'srv',
channel: 'chan1',
users: ['user3', 'user2', '@user4', 'user1', '+user5']
});
expect(state).toEqual({
srv: {
chan1: {
name: 'chan1',
joined: true,
users: [
{ mode: '', nick: 'user3', renderName: 'user3' },
{ mode: '', nick: 'user2', renderName: 'user2' },
{ mode: 'o', nick: 'user4', renderName: '@user4' },
{ mode: '', nick: 'user1', renderName: 'user1' },
{ mode: 'v', nick: 'user5', renderName: '+user5' }
]
}
}
});
});
it('handles SOCKET_TOPIC', () => {
let state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
state = reducer(state, {
type: actions.socket.TOPIC,
network: 'srv',
channel: 'chan1',
topic: 'the topic'
});
expect(state).toMatchObject({
srv: {
chan1: {
topic: 'the topic'
}
}
});
});
it('handles SOCKET_MODE', () => {
let state = reducer(undefined, socket_join('srv', 'chan1', 'nick1'));
state = reducer(state, socket_join('srv', 'chan1', 'nick2'));
state = reducer(state, socket_join('srv', 'chan2', 'nick2'));
state = reducer(state, socket_mode('srv', 'chan1', 'nick1', 'o', ''));
expect(state).toMatchObject({
srv: {
chan1: {
users: [
{ mode: 'o', nick: 'nick1', renderName: '@nick1' },
{ mode: '', nick: 'nick2', renderName: 'nick2' }
]
},
chan2: {
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
}
}
});
state = reducer(state, socket_mode('srv', 'chan1', 'nick1', 'v', 'o'));
state = reducer(state, socket_mode('srv', 'chan1', 'nick2', 'o', ''));
state = reducer(state, socket_mode('srv', 'chan2', 'not_there', 'x', ''));
expect(state).toMatchObject({
srv: {
chan1: {
users: [
{ mode: 'v', nick: 'nick1', renderName: '+nick1' },
{ mode: 'o', nick: 'nick2', renderName: '@nick2' }
]
},
chan2: {
users: [{ mode: '', nick: 'nick2', renderName: 'nick2' }]
}
}
});
});
it('handles channels from INIT', () => {
const state = reducer(undefined, {
type: actions.INIT,
channels: [
{ network: 'srv', name: 'chan1', topic: 'the topic' },
{ network: 'srv', name: 'chan2', joined: true },
{ network: 'srv2', name: 'chan1' }
]
});
expect(state).toEqual({
srv: {
chan1: { name: 'chan1', topic: 'the topic', users: [] },
chan2: { name: 'chan2', joined: true, users: [] }
},
srv2: {
chan1: { name: 'chan1', users: [] }
}
});
});
it('handles networks from INIT', () => {
const state = reducer(undefined, {
type: actions.INIT,
networks: [{ host: '127.0.0.1' }, { host: 'thehost' }]
});
expect(state).toEqual({
'127.0.0.1': {},
thehost: {}
});
});
it('optimistically adds the network on CONNECT', () => {
const state = reducer(
undefined,
connect({ host: '127.0.0.1', nick: 'nick' })
);
expect(state).toEqual({
'127.0.0.1': {}
});
});
it('removes the network on DISCONNECT', () => {
let state = {
srv: {},
srv2: {}
};
state = reducer(state, {
type: actions.DISCONNECT,
network: 'srv2'
});
expect(state).toEqual({
srv: {}
});
});
});
function socket_join(network, channel, user) {
return {
type: actions.socket.JOIN,
network,
user,
channels: [channel]
};
}
function socket_mode(network, channel, user, add, remove) {
return {
type: actions.socket.MODE,
network,
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 networks 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,303 @@
import reducer, { broadcast, getMessageTab } from '../messages';
import * as actions from '../actions';
import appReducer from '../app';
import { unix } from 'utils';
describe('message reducer', () => {
it('adds the message on ADD_MESSAGE', () => {
const state = reducer(undefined, {
type: actions.ADD_MESSAGE,
network: 'srv',
tab: '#chan1',
message: {
from: 'foo',
content: 'msg'
}
});
expect(state).toMatchObject({
srv: {
'#chan1': [
{
from: 'foo',
content: [{ type: 'text', text: 'msg' }]
}
]
}
});
});
it('adds all the messages on ADD_MESSAGES', () => {
const state = reducer(undefined, {
type: actions.ADD_MESSAGES,
network: '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: [{ type: 'text', text: 'msg' }]
},
{
from: 'bar',
content: [{ type: 'text', text: 'msg' }]
}
],
'#chan2': [
{
from: 'foo',
content: [{ type: 'text', text: 'msg' }]
}
]
}
});
});
it('handles prepending of messages on ADD_MESSAGES', () => {
let state = {
srv: {
'#chan1': [{ id: 0 }]
}
};
state = reducer(state, {
type: actions.ADD_MESSAGES,
network: '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(1990, 0, 3) }]
}
};
state = reducer(state, {
type: actions.ADD_MESSAGES,
network: 'srv',
tab: '#chan1',
prepend: true,
messages: [
{ id: 1, time: unix(new Date(1990, 0, 1)) },
{ id: 2, time: unix(new Date(1990, 0, 2)) }
]
});
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,
network: '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(1990, 0, 1) }]
}
};
state = reducer(state, {
type: actions.ADD_MESSAGES,
network: 'srv',
tab: '#chan1',
messages: [
{ id: 1, time: unix(new Date(1990, 0, 2)) },
{ id: 2, time: unix(new Date(1990, 0, 3)) },
{ id: 3, time: unix(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).toMatchObject([
{ type: 'text', text: 'test' }
]);
expect(messages.srv['#chan3']).toHaveLength(1);
expect(messages.srv['#chan3'][0].content).toMatchObject([
{ type: 'text', text: 'test' }
]);
});
it('deletes all messages related to network when disconnecting', () => {
let state = {
srv: {
'#chan1': [{ content: 'msg1' }, { content: 'msg2' }],
'#chan2': [{ content: 'msg' }]
},
srv2: {
'#chan1': [{ content: 'msg' }]
}
};
state = reducer(state, {
type: actions.DISCONNECT,
network: '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,
network: '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,
network: '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,89 +1,88 @@
import Immutable from 'immutable';
import reducer, { connect, setServerName } from '../servers';
import reducer, { connect, setNetworkName } from '../networks';
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', {}));
describe('network reducer', () => {
it('adds the network on CONNECT', () => {
let state = reducer(
undefined,
connect({ host: '127.0.0.1', nick: 'nick' })
);
expect(state.toJS()).toEqual({
expect(state).toEqual({
'127.0.0.1': {
name: '127.0.0.1',
nick: 'nick',
editedNick: null,
status: {
connected: false,
error: null
}
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': {
name: '127.0.0.1',
nick: 'nick',
editedNick: null,
status: {
connected: false,
error: null
}
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': {
name: '127.0.0.1',
nick: 'nick',
editedNick: null,
status: {
connected: false,
error: null
}
connected: false,
error: null,
features: {}
},
'127.0.0.2': {
name: 'srv',
nick: 'nick',
editedNick: null,
status: {
connected: false,
error: null
}
connected: false,
error: null,
features: {}
}
});
});
it('removes the server on DISCONNECT', () => {
let state = Immutable.fromJS({
it('removes the network on DISCONNECT', () => {
let state = {
srv: {},
srv2: {}
});
};
state = reducer(state, {
type: actions.DISCONNECT,
server: 'srv2'
network: 'srv2'
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
srv: {}
});
});
it('handles SET_SERVER_NAME', () => {
let state = Immutable.fromJS({
it('handles SET_NETWORK_NAME', () => {
let state = {
srv: {
name: 'cake'
}
});
};
state = reducer(state, setServerName('pie', 'srv'));
state = reducer(state, setNetworkName('pie', 'srv'));
expect(state.toJS()).toEqual({
expect(state).toEqual({
srv: {
name: 'pie'
}
@ -91,15 +90,18 @@ 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',
network: '127.0.0.1',
nick: 'nick2',
editing: true
});
expect(state.toJS()).toMatchObject({
expect(state).toMatchObject({
'127.0.0.1': {
name: '127.0.0.1',
nick: 'nick',
@ -109,20 +111,23 @@ 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',
network: '127.0.0.1',
nick: 'nick2',
editing: true
});
state = reducer(state, {
type: actions.SET_NICK,
server: '127.0.0.1',
network: '127.0.0.1',
nick: ''
});
expect(state.toJS()).toMatchObject({
expect(state).toMatchObject({
'127.0.0.1': {
name: '127.0.0.1',
nick: 'nick',
@ -132,15 +137,18 @@ 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',
network: '127.0.0.1',
oldNick: 'nick',
newNick: 'nick2'
});
expect(state.toJS()).toMatchObject({
expect(state).toMatchObject({
'127.0.0.1': {
name: '127.0.0.1',
nick: 'nick2',
@ -150,19 +158,22 @@ 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',
network: '127.0.0.1',
nick: 'nick2',
editing: true
});
state = reducer(state, {
type: actions.socket.NICK_FAIL,
server: '127.0.0.1'
network: '127.0.0.1'
});
expect(state.toJS()).toMatchObject({
expect(state).toMatchObject({
'127.0.0.1': {
name: '127.0.0.1',
nick: 'nick',
@ -171,87 +182,79 @@ describe('server reducer', () => {
});
});
it('adds the servers on SOCKET_SERVERS', () => {
it('adds the networks on INIT', () => {
let state = reducer(undefined, {
type: actions.socket.SERVERS,
data: [
type: actions.INIT,
networks: [
{
host: '127.0.0.1',
name: 'stuff',
nick: 'nick',
status: {
connected: true
}
connected: true
},
{
host: '127.0.0.2',
name: 'stuffz',
nick: 'nick2',
status: {
connected: false
}
},
connected: false
}
]
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
'127.0.0.1': {
name: 'stuff',
nick: 'nick',
editedNick: null,
status: {
connected: true,
error: null
}
connected: true,
features: {}
},
'127.0.0.2': {
name: 'stuffz',
nick: 'nick2',
editedNick: null,
status: {
connected: false,
error: null
}
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,
server: '127.0.0.1',
network: '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,
status: {
connected: true,
error: null
}
connected: true,
features: {}
}
});
state = reducer(state, {
type: actions.socket.CONNECTION_UPDATE,
server: '127.0.0.1',
network: '127.0.0.1',
connected: false,
error: 'Bad stuff happened'
});
expect(state.toJS()).toEqual({
expect(state).toEqual({
'127.0.0.1': {
name: '127.0.0.1',
nick: 'nick',
editedNick: null,
status: {
connected: false,
error: 'Bad stuff happened'
}
connected: false,
error: 'Bad stuff happened',
features: {}
}
});
});

View File

@ -1,25 +1,23 @@
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({
selected: { server: 'srv', name: '#chan' },
history: [
{ server: 'srv', name: '#chan' }
]
expect(state).toEqual({
selected: { network: 'srv', name: '#chan' },
history: [{ network: 'srv', name: '#chan' }]
});
state = reducer(state, setSelectedTab('srv', 'user1'));
expect(state.toJS()).toEqual({
selected: { server: 'srv', name: 'user1' },
expect(state).toEqual({
selected: { network: 'srv', name: 'user1' },
history: [
{ server: 'srv', name: '#chan' },
{ server: 'srv', name: 'user1' }
{ network: 'srv', name: '#chan' },
{ network: 'srv', name: 'user1' }
]
});
});
@ -32,15 +30,15 @@ describe('tab reducer', () => {
state = reducer(state, {
type: actions.PART,
server: 'srv',
network: 'srv',
channels: ['#chan']
});
expect(state.toJS()).toEqual({
selected: { server: 'srv', name: '#chan3' },
expect(state).toEqual({
selected: { network: 'srv', name: '#chan3' },
history: [
{ server: 'srv1', name: 'bob' },
{ server: 'srv', name: '#chan3' }
{ network: 'srv1', name: 'bob' },
{ network: 'srv', name: '#chan3' }
]
});
});
@ -53,21 +51,21 @@ describe('tab reducer', () => {
state = reducer(state, {
type: actions.CLOSE_PRIVATE_CHAT,
server: 'srv1',
network: 'srv1',
nick: 'bob'
});
expect(state.toJS()).toEqual({
selected: { server: 'srv', name: '#chan3' },
expect(state).toEqual({
selected: { network: 'srv', name: '#chan3' },
history: [
{ server: 'srv', name: '#chan' },
{ server: 'srv', name: '#chan' },
{ server: 'srv', name: '#chan3' }
{ network: 'srv', name: '#chan' },
{ network: 'srv', name: '#chan' },
{ network: 'srv', name: '#chan3' }
]
});
});
it('removes all tabs related to server from history on DISCONNECT', () => {
it('removes all tabs related to network from history on DISCONNECT', () => {
let state = reducer(undefined, setSelectedTab('srv', '#chan'));
state = reducer(state, setSelectedTab('srv1', 'bob'));
state = reducer(state, setSelectedTab('srv', '#chan'));
@ -75,43 +73,42 @@ describe('tab reducer', () => {
state = reducer(state, {
type: actions.DISCONNECT,
server: 'srv',
network: 'srv'
});
expect(state.toJS()).toEqual({
selected: { server: 'srv', name: '#chan3' },
history: [
{ server: 'srv1', name: 'bob' },
]
expect(state).toEqual({
selected: { network: 'srv', name: '#chan3' },
history: [{ network: 'srv1', name: 'bob' }]
});
});
it('clears the tab when navigating to a non-tab page', () => {
let state = reducer(undefined, setSelectedTab('srv', '#chan'));
state = reducer(state, locationChanged('settings'));
state = reducer(state, locationChanged('settings', {}, {}));
expect(state.toJS()).toEqual({
selected: { server: null, name: null },
history: [
{ server: 'srv', name: '#chan' }
]
expect(state).toEqual({
selected: {},
history: [{ network: 'srv', name: '#chan' }]
});
});
it('selects the tab and adds it to history when navigating to a tab', () => {
const state = reducer(undefined,
locationChanged('chat', {
server: 'srv',
name: '#chan'
})
const state = reducer(
undefined,
locationChanged(
'chat',
{
network: 'srv',
name: '#chan'
},
{}
)
);
expect(state.toJS()).toEqual({
selected: { server: 'srv', name: '#chan' },
history: [
{ server: 'srv', name: '#chan' }
]
expect(state).toEqual({
selected: { network: 'srv', name: '#chan' },
history: [{ network: 'srv', name: '#chan' }]
});
});
});

View File

@ -1,11 +1,15 @@
export const INIT = 'INIT';
export const APP_SET = 'APP_SET';
export const INVITE = 'INVITE';
export const JOIN = 'JOIN';
export const KICK = 'KICK';
export const KICKED = 'KICKED';
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,6 +23,9 @@ 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';
@ -30,13 +37,14 @@ 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 SET_NETWORK_NAME = 'SET_NETWORK_NAME';
export const WHOIS = 'WHOIS';
export const SET_CERT = 'SET_CERT';
export const SET_CERT_ERROR = 'SET_CERT_ERROR';
export const SET_KEY = 'SET_KEY';
export const UPLOAD_CERT = 'UPLOAD_CERT';
export const SETTINGS_SET = 'SETTINGS_SET';
export const SELECT_TAB = 'SELECT_TAB';
@ -59,18 +67,22 @@ function createSocketActions(types) {
export const socket = createSocketActions([
'cert_fail',
'cert_success',
'channels',
'channel_forward',
'channel_search',
'connected',
'connection_update',
'error',
'features',
'join',
'message',
'mode',
'nick_fail',
'nick',
'part',
'kick',
'pm',
'quit',
'search',
'servers',
'topic',
'users'
]);

65
client/js/state/app.js Normal file
View File

@ -0,0 +1,65 @@
import createReducer from 'utils/createReducer';
import * as actions from './actions';
export const getApp = state => state.app;
export const getConnected = state => state.app.connected;
export const getWrapWidth = state => state.app.wrapWidth;
export const getCharWidth = state => state.app.charWidth;
export const getWindowWidth = state => state.app.windowWidth;
export const getConnectDefaults = state => state.app.connectDefaults;
const initialState = {
connected: false,
wrapWidth: 0,
charWidth: 0,
windowWidth: 0,
connectDefaults: {
name: '',
host: '',
port: '',
channels: [],
ssl: false,
password: false,
readonly: false,
showDetails: false
},
hexIP: false,
newVersionAvailable: false,
installable: null
};
export default createReducer(initialState, {
[actions.APP_SET](state, { key, value }) {
if (typeof key === 'object') {
Object.assign(state, key);
} else {
state[key] = value;
}
},
[actions.socket.CONNECTED](state, { connected }) {
state.connected = connected;
},
[actions.UPDATE_MESSAGE_HEIGHT](state, action) {
state.wrapWidth = action.wrapWidth;
state.charWidth = action.charWidth;
state.windowWidth = action.windowWidth;
},
[actions.INIT](state, { app }) {
Object.assign(state, app);
}
});
export function appSet(key, value) {
return {
type: actions.APP_SET,
key,
value
};
}
export function setCharWidth(width) {
return appSet('charWidth', width);
}

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, network, q }) {
if (results) {
state.end = false;
if (start > 0) {
state.results.push(...results);
} else {
state.results = results;
if (!q) {
state.topCache[network] = 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(network, q, start) {
return {
type: actions.CHANNEL_SEARCH,
network,
q,
socket: {
type: 'channel_search',
data: { network, q, start }
}
};
}

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

@ -0,0 +1,332 @@
import { createSelector } from 'reselect';
import get from 'lodash/get';
import sortBy from 'lodash/sortBy';
import createReducer from 'utils/createReducer';
import { trimPrefixChar, 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, network, channel) {
if (!state[network]) {
state[network] = {};
}
if (channel && !state[network][channel]) {
state[network][channel] = {
name: channel,
users: [],
joined: false
};
}
return state[network][channel];
}
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(network => ({
address: network,
channels: sortBy(channels[network], channel =>
trimPrefixChar(channel.name, '#').toLowerCase()
)
})),
network => network.address.toLowerCase()
)
);
export const getSelectedChannel = createSelector(
getSelectedTab,
getChannels,
(tab, channels) => get(channels, [tab.network, tab.name])
);
export const getSelectedChannelUsers = createSelector(
getSelectedChannel,
channel => {
if (channel) {
return channel.users.concat().sort(compareUsers);
}
return [];
}
);
export default createReducer(
{},
{
[actions.JOIN](state, { network, channels }) {
channels.forEach(channel => init(state, network, channel));
},
[actions.PART](state, { network, channels }) {
channels.forEach(channel => delete state[network][channel]);
},
[actions.socket.JOIN](state, { network, channels, user }) {
const channel = channels[0];
const chan = init(state, network, channel);
chan.name = channel;
chan.joined = true;
chan.users.push(createUser(user));
},
[actions.socket.CHANNEL_FORWARD](state, action) {
init(state, action.network, action.new);
delete state[action.network][action.old];
},
[actions.socket.PART](state, { network, channel, user }) {
if (state[network][channel]) {
removeUser(state[network][channel].users, user);
}
},
[actions.socket.QUIT](state, { network, user }) {
Object.keys(state[network]).forEach(channel => {
removeUser(state[network][channel].users, user);
});
},
[actions.KICKED](state, { network, channel, user, self }) {
const chan = state[network][channel];
if (self) {
chan.joined = false;
chan.users = [];
} else {
removeUser(chan.users, user);
}
},
[actions.socket.NICK](state, { network, oldNick, newNick }) {
Object.keys(state[network]).forEach(channel => {
const user = find(
state[network][channel].users,
u => u.nick === oldNick
);
if (user) {
user.nick = newNick;
user.renderName = getRenderName(user);
}
});
},
[actions.socket.MODE](state, { network, channel, user, remove, add }) {
const u = find(state[network][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.TOPIC](state, { network, channel, topic }) {
state[network][channel].topic = topic;
},
[actions.socket.USERS](state, { network, channel, users }) {
state[network][channel].users = users.map(nick => loadUser(nick));
},
[actions.INIT](state, { networks, channels, users }) {
if (networks) {
networks.forEach(({ host }) => init(state, host));
}
if (channels) {
channels.forEach(({ network, name, topic, joined }) => {
const chan = init(state, network, name);
chan.joined = joined;
chan.topic = topic;
});
}
if (users) {
state[users.network][users.channel].users = users.users.map(nick =>
loadUser(nick)
);
}
},
[actions.CONNECT](state, { host }) {
init(state, host);
},
[actions.DISCONNECT](state, { network }) {
delete state[network];
}
}
);
export function join(channels, network, selectFirst = true) {
return {
type: actions.JOIN,
channels,
network,
selectFirst,
socket: {
type: 'join',
data: { channels, network }
}
};
}
export function part(channels, network) {
return (dispatch, getState) => {
const action = {
type: actions.PART,
channels,
network
};
const state = getState().channels[network];
const joined = channels.filter(c => state[c] && state[c].joined);
if (joined.length > 0) {
action.socket = {
type: 'part',
data: {
channels: joined,
network
}
};
}
dispatch(action);
dispatch(updateSelection());
};
}
export function invite(user, channel, network) {
return {
type: actions.INVITE,
user,
channel,
network,
socket: {
type: 'invite',
data: { user, channel, network }
}
};
}
export function kick(user, channel, network) {
return {
type: actions.KICK,
user,
channel,
network,
socket: {
type: 'kick',
data: { user, channel, network }
}
};
}
export function kicked(network, channel, user) {
return (dispatch, getState) => {
const nick = getState().networks[network]?.nick;
dispatch({
type: actions.KICKED,
network,
channel,
user,
self: nick === user
});
};
}
export function setTopic(topic, channel, network) {
return {
type: actions.SET_TOPIC,
topic,
channel,
network,
socket: {
type: 'topic',
data: { topic, channel, network }
}
};
}

View File

@ -1,11 +1,13 @@
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 networks from './networks';
import privateChats from './privateChats';
import search from './search';
import servers from './servers';
import settings from './settings';
import tab from './tab';
import ui from './ui';
@ -18,11 +20,13 @@ export default function createReducer(router) {
router,
app,
channels,
channelSearch,
input,
messages,
modals,
networks,
privateChats,
search,
servers,
settings,
tab,
ui

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

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

@ -0,0 +1,663 @@
import { createSelector } from 'reselect';
import has from 'lodash/has';
import {
findBreakpoints,
messageHeight,
linkify,
timestamp,
isChannel,
formatDate,
unix
} from 'utils';
import colorify from 'utils/colorify';
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.network;
if (has(messages, [tab.network, target])) {
return messages[tab.network][target];
}
return [];
}
);
export const getHasMoreMessages = createSelector(
getSelectedMessages,
messages => {
const first = messages[0];
return first && first.next;
}
);
function init(state, network, tab) {
if (!state[network]) {
state[network] = {};
}
if (!state[network][tab]) {
state[network][tab] = [];
}
}
function initNetworks(state, networks = []) {
networks.forEach(({ host }) => {
state[host] = {};
});
}
const collapsedEvents = ['join', 'part', 'quit', 'nick'];
function shouldCollapse(msg1, msg2) {
return (
msg1.events &&
msg2.events &&
collapsedEvents.indexOf(msg1.events[0].type) !== -1 &&
collapsedEvents.indexOf(msg2.events[0].type) !== -1
);
}
const blocks = {
nick: nick => ({ type: 'nick', text: nick }),
text: text => ({ type: 'text', text }),
events: count => ({ type: 'events', text: `${count} more` })
};
const eventVerbs = {
join: 'joined',
part: 'left',
quit: 'quit'
};
function renderEvent(result, type, events) {
const ending = eventVerbs[type];
if (result.length > 1) {
result[result.length - 1].text += ', ';
}
if (events.length === 1) {
result.push(blocks.nick(events[0][0]));
result.push(blocks.text(` ${ending}`));
} else if (events.length === 2) {
result.push(blocks.nick(events[0][0]));
result.push(blocks.text(' and '));
result.push(blocks.nick(events[1][0]));
result.push(blocks.text(` ${ending}`));
} else if (events.length > 2) {
result.push(blocks.nick(events[0][0]));
result.push(blocks.text(', '));
result.push(blocks.nick(events[1][0]));
result.push(blocks.text(' and '));
result.push(blocks.events(events.length - 2));
result.push(blocks.text(` ${ending}`));
}
}
function renderEvents(events) {
const first = events[0];
if (first.type === 'kick') {
const [kicked, by] = first.params;
return [blocks.nick(by), blocks.text(' kicked '), blocks.nick(kicked)];
}
if (first.type === 'topic') {
const [nick, topic] = first.params;
if (!topic) {
return [blocks.nick(nick), blocks.text(' cleared the topic')];
}
return [
blocks.nick(nick),
blocks.text(' changed the topic to: '),
...colorify(linkify(topic))
];
}
const byType = {};
for (let i = events.length - 1; i >= 0; i--) {
const event = events[i];
const [nick] = event.params;
if (!byType[event.type]) {
byType[event.type] = [event.params];
} else if (byType[event.type].indexOf(nick) === -1) {
byType[event.type].push(event.params);
}
}
const result = [];
if (byType.join) {
renderEvent(result, 'join', byType.join);
}
if (byType.part) {
renderEvent(result, 'part', byType.part);
}
if (byType.quit) {
renderEvent(result, 'quit', byType.quit);
}
if (byType.nick) {
if (result.length > 1) {
result[result.length - 1].text += ', ';
}
const [oldNick, newNick] = byType.nick[0];
result.push(blocks.nick(oldNick));
result.push(blocks.text(' changed nick to '));
result.push(blocks.nick(newNick));
if (byType.nick.length > 1) {
result.push(blocks.text(' and '));
result.push(blocks.events(byType.nick.length - 1));
result.push(blocks.text(' changed nick'));
}
}
return result;
}
let nextID = 0;
function initMessage(
state,
message,
network,
tab,
wrapWidth,
charWidth,
windowWidth,
prepend
) {
const messages = state[network][tab];
if (messages.length > 0 && !prepend) {
const lastMessage = messages[messages.length - 1];
if (shouldCollapse(lastMessage, message)) {
lastMessage.events.push(message.events[0]);
lastMessage.content = renderEvents(lastMessage.events);
[lastMessage.breakpoints, lastMessage.length] = findBreakpoints(
lastMessage.content
);
lastMessage.height = messageHeight(
lastMessage,
wrapWidth,
charWidth,
6 * charWidth,
windowWidth
);
return false;
}
}
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;
}
if (message.events) {
message.type = 'info';
message.content = renderEvents(message.events);
} else {
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);
}
}
if (!message.events) {
message.content = colorify(linkify(message.content));
}
[message.breakpoints, message.length] = findBreakpoints(message.content);
message.height = messageHeight(
message,
wrapWidth,
charWidth,
6 * charWidth,
windowWidth
);
message.indent = 6 * charWidth;
return true;
}
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(
state,
messages,
network,
tab,
wrapWidth,
charWidth,
windowWidth
) {
const msgs = [];
for (let i = 0; i < messages.length; i++) {
const message = messages[i];
initMessage(
state,
message,
network,
tab,
wrapWidth,
charWidth,
windowWidth,
true
);
if (i > 0 && !isSameDay(messages[i - 1].date, message.date)) {
msgs.push(createDateMessage(message.date));
}
msgs.push(message);
}
const m = state[network][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, network, tab, state) {
const messages = state[network][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,
{ network, tab, message, wrapWidth, charWidth, windowWidth }
) {
init(state, network, tab);
const shouldAdd = initMessage(
state,
message,
network,
tab,
wrapWidth,
charWidth,
windowWidth
);
if (shouldAdd) {
reducerAddMessage(message, network, tab, state);
}
},
[actions.ADD_MESSAGES](
state,
{ network, tab, messages, prepend, wrapWidth, charWidth, windowWidth }
) {
if (prepend) {
init(state, network, tab);
reducerPrependMessages(
state,
messages,
network,
tab,
wrapWidth,
charWidth,
windowWidth
);
} else {
if (!messages[0].tab) {
init(state, network, tab);
}
messages.forEach(message => {
if (message.tab) {
init(state, network, message.tab);
}
const shouldAdd = initMessage(
state,
message,
network,
message.tab || tab,
wrapWidth,
charWidth,
windowWidth
);
if (shouldAdd) {
reducerAddMessage(message, network, message.tab || tab, state);
}
});
}
},
[actions.DISCONNECT](state, { network }) {
delete state[network];
},
[actions.PART](state, { network, channels }) {
channels.forEach(channel => delete state[network][channel]);
},
[actions.CLOSE_PRIVATE_CHAT](state, { network, nick }) {
delete state[network][nick];
},
[actions.socket.CHANNEL_FORWARD](state, { network, old }) {
if (state[network]) {
delete state[network][old];
}
},
[actions.UPDATE_MESSAGE_HEIGHT](
state,
{ wrapWidth, charWidth, windowWidth }
) {
Object.keys(state).forEach(network =>
Object.keys(state[network]).forEach(target =>
state[network][target].forEach(message => {
if (message.type === 'date') {
return;
}
message.height = messageHeight(
message,
wrapWidth,
charWidth,
6 * charWidth,
windowWidth
);
})
)
);
},
[actions.INIT](state, { networks }) {
initNetworks(state, networks);
},
[actions.socket.NETWORKS](state, { data }) {
initNetworks(state, data);
}
}
);
export function getMessageTab(network, to) {
if (!to || to === '*' || (!isChannel(to) && to.indexOf('.') !== -1)) {
return network;
}
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 (tab.name) {
dispatch({
type: actions.FETCH_MESSAGES,
socket: {
type: 'fetch_messages',
data: {
network: tab.network,
channel: tab.name,
next: first.id
}
}
});
}
};
}
export function addFetchedMessages(network, tab) {
return {
type: actions.ADD_FETCHED_MESSAGES,
network,
tab
};
}
export function updateMessageHeight(wrapWidth, charWidth, windowWidth) {
return {
type: actions.UPDATE_MESSAGE_HEIGHT,
wrapWidth,
charWidth,
windowWidth
};
}
export function sendMessage(content, to, network) {
return (dispatch, getState) => {
const state = getState();
const { wrapWidth, charWidth, windowWidth } = getApp(state);
dispatch({
type: actions.ADD_MESSAGE,
network,
tab: to,
message: {
from: state.networks[network].nick,
content
},
wrapWidth,
charWidth,
windowWidth,
socket: {
type: 'message',
data: { content, to, network }
}
});
};
}
export function addMessage(message, network, to) {
const tab = getMessageTab(network, to);
return (dispatch, getState) => {
const { wrapWidth, charWidth, windowWidth } = getApp(getState());
dispatch({
type: actions.ADD_MESSAGE,
network,
tab,
message,
wrapWidth,
charWidth,
windowWidth
});
};
}
export function addMessages(messages, network, to, prepend, next) {
const tab = getMessageTab(network, to);
return (dispatch, getState) => {
const state = getState();
if (next) {
messages[0].id = next;
messages[0].next = true;
}
const { wrapWidth, charWidth, windowWidth } = getApp(state);
dispatch({
type: actions.ADD_MESSAGES,
network,
tab,
messages,
prepend,
wrapWidth,
charWidth,
windowWidth
});
};
}
export function addEvent(network, tab, type, ...params) {
return addMessage(
{
type: 'info',
events: [
{
type,
params,
time: unix()
}
]
},
network,
tab
);
}
export function broadcastEvent(network, channels, type, ...params) {
const now = unix();
return addMessages(
channels.map(channel => ({
type: 'info',
tab: channel,
events: [
{
type,
params,
time: now
}
]
})),
network
);
}
export function broadcast(message, network, channels) {
return addMessages(
channels.map(channel => ({
tab: channel,
content: message,
type: 'info'
})),
network
);
}
export function print(message, network, channel, type) {
if (Array.isArray(message)) {
return addMessages(
message.map(line => ({
content: line,
type
})),
network,
channel
);
}
return addMessage(
{
content: message,
type
},
network,
channel
);
}
export function inform(message, network, channel) {
return print(message, network, channel, 'info');
}
export function runCommand(command, channel, network) {
return {
type: actions.COMMAND,
command,
channel,
network
};
}
export function raw(message, network) {
return {
type: actions.RAW,
message,
network,
socket: {
type: 'raw',
data: { message, network }
}
};
}

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

229
client/js/state/networks.js Normal file
View File

@ -0,0 +1,229 @@
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 getNetworks = state => state.networks;
export const getCurrentNick = createSelector(
getNetworks,
getSelectedTab,
(networks, tab) => {
if (!networks[tab.network]) {
return;
}
const { editedNick } = networks[tab.network];
if (editedNick === null) {
return networks[tab.network].nick;
}
return editedNick;
}
);
export const getCurrentNetworkName = createSelector(
getNetworks,
getSelectedTab,
(networks, tab) => get(networks, [tab.network, 'name'])
);
export const getCurrentNetworkError = createSelector(
getNetworks,
getSelectedTab,
(networks, tab) => get(networks, [tab.network, 'error'], null)
);
export default createReducer(
{},
{
[actions.CONNECT](state, { host, nick, name }) {
if (!state[host]) {
state[host] = {
nick,
editedNick: null,
name: name || host,
connected: false,
error: null,
features: {}
};
}
},
[actions.DISCONNECT](state, { network }) {
delete state[network];
},
[actions.SET_NETWORK_NAME](state, { network, name }) {
state[network].name = name;
},
[actions.SET_NICK](state, { network, nick, editing }) {
if (editing) {
state[network].editedNick = nick;
} else if (nick === '') {
state[network].editedNick = null;
}
},
[actions.socket.NICK](state, { network, oldNick, newNick }) {
if (!oldNick || oldNick === state[network].nick) {
state[network].nick = newNick;
state[network].editedNick = null;
}
},
[actions.socket.NICK_FAIL](state, { network }) {
state[network].editedNick = null;
},
[actions.INIT](state, { networks }) {
if (networks) {
networks.forEach(
({ host, name = host, nick, connected, error, features = {} }) => {
state[host] = {
name,
nick,
connected,
error,
features,
editedNick: null
};
}
);
}
},
[actions.socket.CONNECTION_UPDATE](state, { network, connected, error }) {
if (state[network]) {
state[network].connected = connected;
state[network].error = error;
}
},
[actions.socket.FEATURES](state, { network, features }) {
const srv = state[network];
if (srv) {
srv.features = features;
if (features.NETWORK && srv.name === network) {
srv.name = features.NETWORK;
}
}
}
}
);
export function connect(config) {
return {
type: actions.CONNECT,
...config,
socket: {
type: 'connect',
data: config
}
};
}
export function disconnect(network) {
return dispatch => {
dispatch({
type: actions.DISCONNECT,
network,
socket: {
type: 'quit',
data: { network }
}
});
dispatch(updateSelection());
};
}
export function reconnect(network, settings) {
return {
type: actions.RECONNECT,
network,
settings,
socket: {
type: 'reconnect',
data: {
...settings,
network
}
}
};
}
export function whois(user, network) {
return {
type: actions.WHOIS,
user,
network,
socket: {
type: 'whois',
data: { user, network }
}
};
}
export function away(message, network) {
return {
type: actions.AWAY,
message,
network,
socket: {
type: 'away',
data: { message, network }
}
};
}
export function setNick(nick, network, editing) {
nick = nick.trim().replace(' ', '');
const action = {
type: actions.SET_NICK,
nick,
network,
editing
};
if (!editing && nick !== '') {
action.socket = {
type: 'nick',
data: {
newNick: nick,
network
}
};
}
return action;
}
export function isValidNetworkName(name) {
return name.trim() !== '';
}
export function setNetworkName(name, network) {
const action = {
type: actions.SET_NETWORK_NAME,
name,
network
};
if (isValidNetworkName(name)) {
action.socket = {
type: 'set_network_name',
data: {
name,
network
},
debounce: {
delay: 500,
key: `network_name:${network}`
}
};
}
return action;
}

View File

@ -0,0 +1,86 @@
import sortBy from 'lodash/sortBy';
import { isDM } from 'utils';
import createReducer from 'utils/createReducer';
import { updateSelection } from './tab';
import * as actions from './actions';
export const getPrivateChats = state => state.privateChats;
function open(state, network, nick) {
if (!state[network]) {
state[network] = [];
}
if (!state[network].includes(nick)) {
state[network].push(nick);
state[network] = sortBy(state[network], v => v.toLowerCase());
}
}
export default createReducer(
{},
{
[actions.OPEN_PRIVATE_CHAT](state, action) {
open(state, action.network, action.nick);
},
[actions.CLOSE_PRIVATE_CHAT](state, { network, nick }) {
const i = state[network]?.findIndex(n => n === nick);
if (i !== -1) {
state[network].splice(i, 1);
}
},
[actions.INIT](state, { openDMs }) {
if (openDMs) {
openDMs.forEach(({ network, name }) => {
if (!state[network]) {
state[network] = [];
}
state[network].push(name);
});
}
},
[actions.ADD_MESSAGE](state, { message }) {
if (isDM(message)) {
open(state, message.network, message.from);
}
},
[actions.DISCONNECT](state, { network }) {
delete state[network];
}
}
);
export function openPrivateChat(network, nick) {
return (dispatch, getState) => {
if (!getState().privateChats[network]?.includes(nick)) {
dispatch({
type: actions.OPEN_PRIVATE_CHAT,
network,
nick,
socket: {
type: 'open_dm',
data: { network, name: nick }
}
});
}
};
}
export function closePrivateChat(network, nick) {
return dispatch => {
dispatch({
type: actions.CLOSE_PRIVATE_CHAT,
network,
nick,
socket: {
type: 'close_dm',
data: { network, name: nick }
}
});
dispatch(updateSelection());
};
}

38
client/js/state/search.js Normal file
View File

@ -0,0 +1,38 @@
import createReducer from 'utils/createReducer';
import * as actions from './actions';
const initialState = {
show: false,
results: []
};
export const getSearch = state => state.search;
export default createReducer(initialState, {
[actions.socket.SEARCH](state, { results }) {
state.results = results || [];
},
[actions.TOGGLE_SEARCH](state) {
state.show = !state.show;
}
});
export function searchMessages(network, channel, phrase) {
return {
type: actions.SEARCH_MESSAGES,
network,
channel,
phrase,
socket: {
type: 'search',
data: { network, channel, phrase }
}
};
}
export function toggleSearch() {
return {
type: actions.TOGGLE_SEARCH
};
}

View File

@ -1,10 +1,11 @@
import { createSelector } from 'reselect';
import { getServers } from './servers';
import get from 'lodash/get';
import { getNetworks } from './networks';
import { getSelectedTab } from './tab';
// eslint-disable-next-line import/prefer-default-export
export const getSelectedTabTitle = createSelector(
getSelectedTab,
getServers,
(tab, servers) => tab.name || servers.getIn([tab.server, 'name'])
getNetworks,
(tab, networks) => tab.name || get(networks, [tab.network, 'name'])
);

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

@ -0,0 +1,130 @@
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;
}
},
[actions.INIT](state, { settings }) {
return settings;
}
}
);
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;
}

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

@ -0,0 +1,133 @@
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 = {
network: action.network,
name: action.name
};
state.history.push(state.selected);
}
export const getSelectedTab = state => state.tab.selected;
export default createReducer(initialState, {
[actions.SELECT_TAB]: selectTab,
[actions.JOIN](state, { network, channels, selectFirst }) {
if (selectFirst) {
state.selected = {
network,
name: channels[0]
};
state.history.push(state.selected);
}
},
[actions.PART](state, action) {
state.history = state.history.filter(
tab =>
!(tab.network === action.network && tab.name === action.channels[0])
);
},
[actions.CLOSE_PRIVATE_CHAT](state, action) {
state.history = state.history.filter(
tab => !(tab.network === action.network && tab.name === action.nick)
);
},
[actions.DISCONNECT](state, action) {
state.history = state.history.filter(tab => tab.network !== action.network);
},
[LOCATION_CHANGED](state, action) {
const { route, params } = action;
if (route === 'chat') {
selectTab(state, params);
} else {
state.selected = {};
}
}
});
export function select(network, name, doReplace) {
const navigate = doReplace ? replace : push;
if (name) {
return navigate(`/${network}/${encodeURIComponent(name)}`);
}
return navigate(`/${network}`);
}
export function tabExists(
{ network, name },
{ networks, channels, privateChats }
) {
return (
(name && get(channels, [network, name])) ||
(!name && network && networks[network]) ||
(name && find(privateChats[network], nick => nick === name))
);
}
function parseTabCookie() {
const cookie = Cookie.get('tab');
if (cookie) {
const [network, name = null] = cookie.split(/;(.+)/);
return { network, 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.network, tab.name, true));
}
}
const { networks } = state;
const { history } = state.tab;
const { network } = state.tab.selected;
const networkAddrs = Object.keys(networks);
if (networkAddrs.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.network, tab.name, true));
} else if (networks[network]) {
dispatch(select(network, null, true));
} else {
dispatch(select(networkAddrs.sort()[0], null, true));
}
};
}
export function setSelectedTab(network, name = null) {
return {
type: actions.SELECT_TAB,
network,
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;
}

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

@ -0,0 +1,17 @@
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, {
denylist: [new RegExp('/downloads/')]
})
);

View File

@ -13,8 +13,7 @@ export default class Socket {
jitter: 0.25
});
this.handlers = [];
this.connect();
this.connected = false;
}
connect() {
@ -26,14 +25,18 @@ export default class Socket {
}, this.connectTimeout);
this.ws.onopen = () => {
this.emit('_connected', true);
this.connected = true;
this.emit('connected', { connected: true });
clearTimeout(this.timeoutConnect);
this.backoff.reset();
this.setTimeoutPing();
};
this.ws.onclose = () => {
this.emit('_connected', false);
if (this.connected) {
this.connected = false;
this.emit('connected', { 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,140 @@
import {
trimPrefixChar,
isChannel,
isValidNick,
isValidChannel,
isValidUsername
} from '..';
import linkify from '../linkify';
describe('trimPrefixChar()', () => {
it('trims prefix characters', () => {
expect(trimPrefixChar('##chan', '#')).toBe('chan');
expect(trimPrefixChar('#chan', '#')).toBe('chan');
expect(trimPrefixChar('chan', '#')).toBe('chan');
});
});
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 => ({
type: 'link',
url: proto(href),
text: href
});
const buildText = arr => {
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === 'string') {
arr[i] = {
type: 'text',
text: arr[i]
};
}
}
return arr;
};
it('returns a text block when no matches are found', () =>
['just some text', ''].forEach(input =>
expect(linkify(input)).toStrictEqual([{ type: 'text', text: 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(linkify(input)).toEqual(buildText(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;
}

356
client/js/utils/colorify.js Normal file
View File

@ -0,0 +1,356 @@
export const formatChars = {
bold: 0x02,
italic: 0x1d,
underline: 0x1f,
strikethrough: 0x1e,
color: 0x03,
reverseColor: 0x16,
reset: 0x0f
};
export const colors = {
0: 'white',
1: 'black',
2: 'blue',
3: 'green',
4: 'red',
5: 'brown',
6: 'magenta',
7: 'orange',
8: 'yellow',
9: 'lightgreen',
10: 'cyan',
11: 'lightcyan',
12: 'lightblue',
13: 'pink',
14: 'gray',
15: 'lightgray',
16: '#470000',
17: '#472100',
18: '#474700',
19: '#324700',
20: '#004700',
21: '#00472c',
22: '#004747',
23: '#002747',
24: '#000047',
25: '#2e0047',
26: '#470047',
27: '#47002a',
28: '#740000',
29: '#743a00',
30: '#747400',
31: '#517400',
32: '#007400',
33: '#007449',
34: '#007474',
35: '#004074',
36: '#000074',
37: '#4b0074',
38: '#740074',
39: '#740045',
40: '#b50000',
41: '#b56300',
42: '#b5b500',
43: '#7db500',
44: '#00b500',
45: '#00b571',
46: '#00b5b5',
47: '#0063b5',
48: '#0000b5',
49: '#7500b5',
50: '#b500b5',
51: '#b5006b',
52: '#ff0000',
53: '#ff8c00',
54: '#ffff00',
55: '#b2ff00',
56: '#00ff00',
57: '#00ffa0',
58: '#00ffff',
59: '#008cff',
60: '#0000ff',
61: '#a500ff',
62: '#ff00ff',
63: '#ff0098',
64: '#ff5959',
65: '#ffb459',
66: '#ffff71',
67: '#cfff60',
68: '#6fff6f',
69: '#65ffc9',
70: '#6dffff',
71: '#59b4ff',
72: '#5959ff',
73: '#c459ff',
74: '#ff66ff',
75: '#ff59bc',
76: '#ff9c9c',
77: '#ffd39c',
78: '#ffff9c',
79: '#e2ff9c',
80: '#9cff9c',
81: '#9cffdb',
82: '#9cffff',
83: '#9cd3ff',
84: '#9c9cff',
85: '#dc9cff',
86: '#ff9cff',
87: '#ff94d3',
88: '#000000',
89: '#131313',
90: '#282828',
91: '#363636',
92: '#4d4d4d',
93: '#656565',
94: '#818181',
95: '#9f9f9f',
96: '#bcbcbc',
97: '#e2e2e2',
98: '#ffffff'
};
function tokenize(str) {
const tokens = [];
let colorBuffer = '';
let color = false;
let background = false;
let colorToken;
let start = 0;
let end = 0;
const pushText = () => {
if (end > start) {
tokens.push({
type: 'text',
content: str.slice(start, end)
});
start = end;
}
};
const pushToken = token => {
pushText();
tokens.push(token);
};
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i);
if (color) {
if (charCode >= 48 && charCode <= 57 && colorBuffer.length < 2) {
colorBuffer += str[i];
} else if (charCode === 44 && !background) {
colorToken.color = colors[parseInt(colorBuffer, 10)];
colorBuffer = '';
background = true;
} else {
if (background) {
if (colorBuffer.length > 0) {
colorToken.background = colors[parseInt(colorBuffer, 10)];
} else {
// Trailing comma
start--;
}
} else {
colorToken.color = colors[parseInt(colorBuffer, 10)];
}
start--;
colorBuffer = '';
color = false;
tokens.push(colorToken);
}
} else {
switch (charCode) {
case formatChars.bold:
pushToken({
type: 'bold'
});
break;
case formatChars.italic:
pushToken({
type: 'italic'
});
break;
case formatChars.underline:
pushToken({
type: 'underline'
});
break;
case formatChars.strikethrough:
pushToken({
type: 'strikethrough'
});
break;
case formatChars.color:
pushText();
colorToken = {
type: 'color'
};
color = true;
background = false;
break;
case formatChars.reverseColor:
pushToken({
type: 'reverse'
});
break;
case formatChars.reset:
pushToken({
type: 'reset'
});
break;
default:
start--;
}
}
start++;
end++;
}
if (start === 0) {
return str;
}
pushText();
return tokens;
}
function colorifyString(str, state = {}) {
const tokens = tokenize(str);
if (tokens === str) {
return [tokens, state];
}
const result = [];
let style = state.style || {};
let reverse = state.reverse || false;
const toggle = (prop, value, multiple) => {
if (style[prop]) {
if (multiple) {
const props = style[prop].split(' ');
const i = props.indexOf(value);
if (i !== -1) {
props.splice(i, 1);
} else {
props.push(value);
}
style[prop] = props.join(' ');
} else {
delete style[prop];
}
} else {
style[prop] = value;
}
};
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
switch (token.type) {
case 'bold':
toggle('fontWeight', 700);
break;
case 'italic':
toggle('fontStyle', 'italic');
break;
case 'underline':
toggle('textDecoration', 'underline', true);
break;
case 'strikethrough':
toggle('textDecoration', 'line-through', true);
break;
case 'color':
if (!token.color) {
delete style.color;
delete style.background;
} else if (reverse) {
style.color = token.background;
style.background = token.color;
} else {
style.color = token.color;
style.background = token.background;
}
break;
case 'reverse':
reverse = !reverse;
if (style.color) {
const bg = style.background;
style.background = style.color;
style.color = bg;
}
break;
case 'reset':
style = {};
break;
case 'text':
if (Object.keys(style).length > 0) {
result.push({
type: 'format',
style,
text: token.content
});
style = { ...style };
} else {
result.push({
type: 'text',
text: token.content
});
}
break;
default:
}
}
return [result, { style, reverse }];
}
export default function colorify(blocks) {
if (!blocks) {
return blocks;
}
const result = [];
let colored;
let state;
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
if (block.type === 'text') {
[colored, state] = colorifyString(block.text, state);
if (colored !== block.text) {
result.push(...colored);
} else {
result.push(block);
}
} else {
result.push(block);
}
}
return result;
}

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

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

@ -0,0 +1,226 @@
import padStart from 'lodash/padStart';
export { findBreakpoints, messageHeight } from './messageHeight';
export { default as linkify } from './linkify';
export function isChannel(name) {
// TODO: Handle other channel types
if (typeof name === 'object') {
({ name } = name);
}
return typeof name === 'string' && name[0] === '#';
}
export function stringifyTab(network, name) {
if (typeof network === 'object') {
if (network.name) {
return `${network.network};${network.name}`;
}
return network.network;
}
if (name) {
return `${network};${name}`;
}
return network;
}
function isString(s, maxLength) {
if (!s || typeof s !== 'string') {
return false;
}
if (maxLength && s.length > maxLength) {
return false;
}
return true;
}
export function isDM({ from, to }) {
return !to && from?.indexOf('.') === -1 && !isChannel(from);
}
export function trimPrefixChar(str, char) {
if (!isString(str)) {
return str;
}
let start = 0;
while (str[start] === char) {
start++;
}
if (start > 0) {
return str.slice(start);
}
return str;
}
// 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 (typeof i === 'string') {
i = parseInt(i, 10);
}
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;
export function unix(date) {
if (date) {
return Math.floor(date.getTime() / 1000);
}
return Math.floor(Date.now() / 1000);
}
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

@ -0,0 +1,76 @@
import Autolinker from 'autolinker';
const autolinker = new Autolinker({
stripPrefix: false,
stripTrailingSlash: false
});
function pushText(arr, text) {
const last = arr[arr.length - 1];
if (last?.type === 'text') {
last.text += text;
} else {
arr.push({
type: 'text',
text
});
}
}
function pushLink(arr, url, text) {
arr.push({
type: 'link',
url,
text
});
}
export default function linkify(text) {
if (typeof text !== 'string') {
return text;
}
let matches = autolinker.parseText(text);
if (matches.length === 0) {
return [
{
type: 'text',
text
}
];
}
const result = [];
let pos = 0;
matches = autolinker.compactMatches(matches);
for (let i = 0; i < matches.length; i++) {
const match = matches[i];
if (match.getType() === 'url') {
if (match.offset > pos) {
pushText(result, text.slice(pos, match.offset));
}
pushLink(result, match.getAnchorHref(), match.matchedText);
} else {
pushText(
result,
text.slice(pos, match.offset + match.matchedText.length)
);
}
pos = match.offset + match.matchedText.length;
}
if (pos < text.length) {
if (result[result.length - 1]?.type === 'text') {
result[result.length - 1].text += text.slice(pos);
} else {
pushText(result, text.slice(pos));
}
}
return result;
}

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