Initial stash

This commit is contained in:
Evert Prants 2022-09-25 14:32:00 +03:00
commit fbfbc69c7c
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
37 changed files with 29541 additions and 0 deletions

23
.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

6
.prettierrc Normal file
View File

@ -0,0 +1,6 @@
{
"semi": true,
"tabWidth": 2,
"singleQuote": true,
"trailingComma": "all"
}

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

@ -0,0 +1,13 @@
{
"editor.formatOnSave": true,
"files.insertFinalNewline": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"eslint.validate": [
"typescript",
"typescriptreact",
"html"
],
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
}

46
README.md Normal file
View File

@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

28404
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

48
package.json Normal file
View File

@ -0,0 +1,48 @@
{
"name": "teemant",
"version": "0.1.0",
"private": true,
"dependencies": {
"@icynet/irclib": "git+https://gitlab.icynet.eu/IcyNetwork/irclib/",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.11.59",
"@types/react": "^18.0.21",
"@types/react-dom": "^18.0.6",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"sass": "^1.55.0",
"typescript": "^4.8.3",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"prettier": "^2.7.1"
}
}

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

43
public/index.html Normal file
View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

25
public/manifest.json Normal file
View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

3
public/robots.txt Normal file
View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

8
src/App.scss Normal file
View File

@ -0,0 +1,8 @@
.App {
&,
main {
height: 100vh;
display: flex;
flex-direction: column;
}
}

47
src/App.tsx Normal file
View File

@ -0,0 +1,47 @@
import React, { useEffect, useRef, useState } from 'react';
import './App.scss';
import { ClientView } from './components/ClientView/ClientView';
import { ConnectionForm } from './components/ConnectionForm/ConnectionForm';
import { IRCManager } from './lib/irc-manager';
function App() {
const manager = useRef<IRCManager>();
const [initScreen, setInitScreen] = useState(true);
useEffect(() => {
manager.current = new IRCManager();
manager.current.on('connectionRemoved', () => {
if (!manager.current?.connections.length) {
setInitScreen(true);
}
});
manager.current.on('connectionAdded', () => {
setInitScreen(false);
});
}, []);
return (
<div className="App">
<main>
{initScreen ? (
<ConnectionForm
onSubmit={(nick, channel, host, ssl, port, password) => {
manager.current?.createNewConnection(
nick,
channel.split(','),
host,
ssl,
port,
password,
);
}}
/>
) : (
<>{manager.current && <ClientView manager={manager.current} />}</>
)}
</main>
</div>
);
}
export default App;

View File

@ -0,0 +1,181 @@
import { IIRCLine, IRCConnectionEvents, NickListEvents } from '@icynet/irclib';
import { useEffect, useReducer } from 'react';
import { IRCConnectionWrapper, IRCManager } from '../../lib/irc-manager';
import { BufferActionKind, BufferType } from '../../lib/client-view.types';
import { ClientViewReducer, getBuffer } from '../../lib/client.reducer';
import { MessageBufferWrapper } from '../MessageBufferWrapper/MessageBufferWrapper';
import { ViewTabs } from '../ViewTabs/ViewTabs';
export const ClientView = ({ manager }: { manager: IRCManager }) => {
const [state, dispatch] = useReducer(ClientViewReducer, {
buffers: [],
activeIndex: 0,
});
useEffect(() => {
const firstConnection = manager.connections[0];
dispatch({
type: BufferActionKind.AddBuffer,
payload: {
connection: firstConnection,
toBuffer: {
type: 'server',
name: firstConnection.connection.options.host,
},
},
});
}, [manager.connections]);
useEffect(() => {
const handlers: [
IRCConnectionWrapper,
keyof IRCConnectionEvents,
(...args: any) => void,
][] = [];
manager.connections.forEach((conn) => {
const lineHandler = (line: IIRCLine, processed: boolean) => {
if (processed) return;
let target: BufferType = 'server';
let targetName: string | undefined;
if (line.arguments[1] || (!line.arguments[1] && line.arguments[0])) {
const targetTest = line.arguments[line.arguments.length - 1];
const exists = getBuffer(state, {
connection: conn,
toBuffer: {
name: targetTest,
},
});
if (exists) {
target = exists.type;
targetName = exists.name;
}
}
if (
(line.command === 'NOTICE' || line.command === 'PRIVMSG') &&
line.arguments[0] === conn.connection.options.nick &&
line.user.nickname
) {
dispatch({
type: BufferActionKind.AddBuffer,
payload: {
connection: conn,
toBuffer: {
type: 'user',
name: line.user.nickname,
},
},
});
target = 'user';
targetName = line.user.nickname;
}
dispatch({
type: BufferActionKind.AddBufferLine,
payload: {
connection: conn,
toBuffer: {
type: target,
name: targetName,
},
message: {
type: 'privmsg',
time: new Date(),
sender: line.user
? line.user.nickname || line.user.hostname
: '--',
message: line.trailing,
},
},
});
if (
line.command === 'JOIN' &&
line.user.nickname === conn.connection.options.nick
) {
dispatch({
type: BufferActionKind.AddBuffer,
payload: {
connection: conn,
toBuffer: {
type: 'channel',
name: line.trailing,
},
},
});
}
if (line.command === '332' || line.command === 'TOPIC') {
dispatch({
type: BufferActionKind.SetTopic,
payload: {
connection: conn,
toBuffer: {
type: 'channel',
name: line.arguments[line.arguments.length - 1],
},
topic: line.trailing,
},
});
}
};
conn.connection.on('line', lineHandler);
handlers.push([conn, 'line', lineHandler]);
});
return () =>
handlers.forEach(([main, evt, handler]) =>
main.connection.removeEventListener(evt, handler),
);
}, [manager.connections, state]);
useEffect(() => {
const handlers: [
IRCConnectionWrapper,
keyof NickListEvents,
(...args: any) => void,
][] = [];
manager.connections.forEach((conn) => {
const handler = (channels?: string[]) => {
dispatch({
type: BufferActionKind.UpdateNicklist,
payload: {
connection: conn,
channels,
},
});
};
conn.nicklist.on('update', handler);
handlers.push([conn, 'update', handler]);
});
return () =>
handlers.forEach(([main, evt, handler]) =>
main.nicklist.removeEventListener(evt, handler),
);
}, [manager.connections]);
return (
<>
<ViewTabs
buffers={state.buffers}
activeIndex={state.activeIndex}
setActive={(index) => {
dispatch({
type: BufferActionKind.SetActiveBuffer,
payload: {
activeIndex: index,
},
});
}}
/>
<MessageBufferWrapper state={state} dispatch={dispatch} />
</>
);
};

View File

@ -0,0 +1,78 @@
import { useState } from 'react';
export const ConnectionForm = ({
onSubmit,
}: {
onSubmit: (
nick: string,
channel: string,
host: string,
ssl: boolean,
port: number,
password: string,
) => void;
}) => {
const [nick, setNick] = useState('testuser');
const [host, setHost] = useState('ws.irc.icynet.eu');
const [channel, setChannel] = useState('#squeebot');
const [port, setPort] = useState(443);
const [password, setPassword] = useState('');
const [ssl, setSSL] = useState(true);
return (
<div>
<h1>teemant</h1>
<form
onSubmit={() => {
onSubmit(nick, channel, host, ssl, port, password);
}}
>
<label htmlFor="nick">Nickname</label>
<input
id="nick"
name="nick"
value={nick}
onChange={(e) => setNick(e.target.value)}
/>
<label htmlFor="channel">Channel</label>
<input
id="channel"
name="channel"
value={channel}
onChange={(e) => setChannel(e.target.value)}
/>
<label htmlFor="host">Hostname</label>
<input
id="host"
name="host"
value={host}
onChange={(e) => setHost(e.target.value)}
/>
<label htmlFor="port">Port</label>
<input
id="port"
name="port"
value={port}
onChange={(e) => setPort(parseInt(e.target.value, 10))}
/>
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
name="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<label htmlFor="ssl">Use SSL</label>
<input
id="ssl"
type="checkbox"
name="ssl"
checked={ssl}
onChange={(e) => setSSL(e.target.checked)}
/>
<button type="submit">Connect</button>
</form>
</div>
);
};

View File

@ -0,0 +1,38 @@
.wrapper {
display: flex;
flex-direction: column;
width: 100%;
.topic {
border-bottom: 2px solid #ddd;
padding: 0.25rem;
}
.messages {
display: flex;
flex-direction: column;
align-items: flex-start;
text-align: left;
flex-grow: 1;
overflow: auto;
.message {
display: flex;
flex-direction: row;
gap: 0.5rem;
font-size: 1rem;
font-family: monospace;
white-space: pre-wrap;
}
}
.input {
flex-grow: 1;
font-size: 1.25rem;
&Wrapper {
display: flex;
padding: 0.5rem;
background-color: rgb(235, 235, 235);
}
}
}

View File

@ -0,0 +1,64 @@
import { wrapFormattedText } from '@icynet/irclib';
import styles from './MessageBufferView.module.scss';
import { useState } from 'react';
import ReactDOMServer from 'react-dom/server';
import { ParsedIRCLine } from '../../lib/client-view.types';
import { escapeHtml } from '../../lib/utils/html';
import { MessageText } from '../MessageText/MessageText';
export const MessageBufferView = ({
messages,
topic,
sendMessage,
}: {
messages: ParsedIRCLine[];
topic?: string;
sendMessage: (msg: string) => void;
}) => {
const [message, setMessage] = useState<string>('');
return (
<div className={styles.wrapper}>
{topic && <div className={styles.topic}>{topic}</div>}
<div className={styles.messages}>
{messages.map((msg, index) => (
<span key={index} className={styles.message}>
<span className={styles.time}>
{msg.time.toTimeString().substring(0, 8)}
</span>
<span className={styles.sender}>{msg.sender}</span>
<span
className={styles.message}
dangerouslySetInnerHTML={{
// TODO: fix this fuckin mess
__html: wrapFormattedText(
escapeHtml(msg.message),
(text, fg, bg, fmt) => {
return ReactDOMServer.renderToStaticMarkup(
<MessageText fg={fg} bg={bg} fmt={fmt}>
{text}
</MessageText>,
);
},
),
}}
></span>
</span>
))}
</div>
<div className={styles.inputWrapper}>
<input
value={message}
className={styles.input}
onChange={(e) => setMessage(e.target.value)}
onKeyUp={(e) => {
if (e.key === 'Enter') {
sendMessage(message);
setMessage('');
}
}}
/>
</div>
</div>
);
};

View File

@ -0,0 +1,6 @@
.bufferRow {
display: flex;
flex-direction: row;
flex-grow: 1;
overflow: hidden;
}

View File

@ -0,0 +1,52 @@
import { Dispatch } from 'react';
import {
BufferState,
BufferAction,
BufferActionKind,
} from '../../lib/client-view.types';
import styles from './MessageBufferWrapper.module.scss';
import { MessageBufferView } from '../MessageBufferView/MessageBufferView';
import { NickListView } from '../NickListView/NickListView';
export const MessageBufferWrapper = ({
state,
dispatch,
}: {
state: BufferState;
dispatch: Dispatch<BufferAction>;
}) => {
const buff = state.buffers[state.activeIndex];
return buff ? (
<div className={styles.bufferRow}>
<MessageBufferView
topic={buff.topic}
sendMessage={(msg) => {
if (buff.type === 'channel' || buff.type === 'user') {
buff.connection.connection.write('PRIVMSG %s :%s', buff.name, msg);
dispatch({
type: BufferActionKind.AddBufferLine,
payload: {
connection: buff.connection,
toBuffer: {
type: buff.type,
name: buff.name,
},
message: {
type: 'privmsg',
time: new Date(),
sender: buff.connection.connection.options.nick,
message: msg,
},
},
});
}
}}
messages={buff.lines}
/>
{buff.type === 'channel' && <NickListView nicklist={buff.nicks} />}
</div>
) : (
<></>
);
};

View File

@ -0,0 +1,43 @@
@use 'sass:map';
$irc-color-map: (
'white': rgb(255, 255, 255),
'black': rgb(0, 0, 0),
'blue': rgb(0, 0, 127),
'green': rgb(0, 147, 0),
'red': rgb(255, 0, 0),
'brown': rgb(127, 0, 0),
'purple': rgb(156, 0, 156),
'orange': rgb(252, 127, 0),
'yellow': rgb(255, 255, 0),
'lightgreen': rgb(0, 252, 0),
'cyan': rgb(0, 147, 147),
'lightcyan': rgb(0, 255, 255),
'lightblue': rgb(0, 0, 252),
'pink': rgb(255, 0, 255),
'grey': rgb(127, 127, 127),
'lightgrey': rgb(210, 210, 210),
);
.message {
@each $name, $color in $irc-color-map {
&-fg-#{$name} {
color: $color;
}
&-bg-#{$name} {
background-color: $color;
}
}
.bold {
font-weight: bold;
}
.italics {
font-style: italic;
}
.underline {
text-decoration: underline;
}
}

View File

@ -0,0 +1,27 @@
import { ReactNode } from 'react';
import styles from './MessageText.module.scss';
export const MessageText = ({
children,
fg,
bg,
fmt,
}: {
children: ReactNode;
fg?: string;
bg?: string;
fmt?: string;
}) => (
<span
className={[
styles['message'],
fg ? styles[`message-fg-${fg}`] : undefined,
bg ? styles[`message-bg-${bg}`] : undefined,
fmt ? styles[`message-${fmt}`] : undefined,
]
.filter((item) => item)
.join(' ')}
>
{children}
</span>
);

View File

@ -0,0 +1,7 @@
.list {
display: flex;
flex-direction: column;
min-width: 16vw;
padding-left: 1rem;
border-left: 2px solid #ddd;
}

View File

@ -0,0 +1,15 @@
import { INicklistNick } from '@icynet/irclib';
import styles from './NickListView.module.scss';
export const NickListView = ({ nicklist }: { nicklist?: INicklistNick[] }) => {
return (
<div className={styles.list}>
{nicklist?.map((nick) => (
<span key={nick.nickname} className={styles.nick}>
{nick.prefix && <span className={styles.prefix}>{nick.prefix}</span>}
{nick.nickname}
</span>
))}
</div>
);
};

View File

@ -0,0 +1,22 @@
.tabs {
background-color: #ddd;
.tab {
appearance: none;
border: 0;
padding: 0.75rem 1.25rem;
background-color: rgb(207, 207, 207);
font-size: 1rem;
cursor: pointer;
&:hover,
&:focus-visible {
background-color: rgb(224, 224, 224);
}
&.active {
background-color: rgb(236, 236, 236);
font-weight: bold;
}
}
}

View File

@ -0,0 +1,30 @@
import { MessageBuffer } from '../../lib/client-view.types';
import styles from './ViewTabs.module.scss';
export const ViewTabs = ({
buffers,
activeIndex,
setActive,
}: {
buffers: MessageBuffer[];
activeIndex: number;
setActive: (index: number) => void;
}) => {
return (
<div className={styles.tabs}>
{buffers.map((buff: MessageBuffer, index: number) => (
<button
key={`${buff.connection.name}-${buff.name}`}
className={[styles.tab, index === activeIndex && styles.active].join(
' ',
)}
onClick={() => {
setActive(index);
}}
>
{buff.name}
</button>
))}
</div>
);
};

13
src/index.css Normal file
View File

@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

19
src/index.tsx Normal file
View File

@ -0,0 +1,19 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

View File

@ -0,0 +1,61 @@
import { INicklistNick } from '@icynet/irclib';
import { IRCConnectionWrapper } from './irc-manager';
export type MessageType =
| 'info'
| 'mode'
| 'notice'
| 'privmsg'
| 'join'
| 'leave';
export type BufferType = 'server' | 'channel' | 'user';
export interface ParsedIRCLine {
time: Date;
sender: string;
message: string;
type: MessageType;
highlight?: boolean;
}
export enum BufferActionKind {
AddServerBuffer = 'add-server-buffer',
AddBuffer = 'add-buffer',
AddBufferLine = 'add-buffer-line',
SetActiveBuffer = 'set-active-buffer',
SetTopic = 'set-topic',
UpdateNicklist = 'update-nicklist',
}
export interface BufferActionTarget {
type?: BufferType;
name?: string;
}
export interface BufferActionPayload {
connection?: IRCConnectionWrapper;
toBuffer?: BufferActionTarget;
message?: ParsedIRCLine;
channels?: string[];
topic?: string;
activeIndex?: number;
}
export interface BufferAction {
type: BufferActionKind;
payload: BufferActionPayload;
}
export interface MessageBuffer {
type: BufferType;
name: string;
lines: ParsedIRCLine[];
nicks?: INicklistNick[];
topic?: string;
connection: IRCConnectionWrapper;
}
export interface BufferState {
buffers: MessageBuffer[];
activeIndex: number;
}

112
src/lib/client.reducer.ts Normal file
View File

@ -0,0 +1,112 @@
import {
BufferState,
BufferActionPayload,
MessageBuffer,
BufferAction,
BufferActionKind,
} from './client-view.types';
export const getBuffer = (
state: BufferState,
payload: BufferActionPayload,
): MessageBuffer | undefined => {
return state.buffers.find(
(item) =>
(payload.connection
? payload.connection.name === item.connection.name
: true) &&
(payload.toBuffer
? (payload.toBuffer.type
? payload.toBuffer.type === item.type
: true) &&
(payload.toBuffer.name ? payload.toBuffer.name === item.name : true)
: true),
);
};
export const ClientViewReducer = (
state: BufferState,
action: BufferAction,
): BufferState => {
const { type, payload } = action;
if (!payload) return state;
if (payload.connection) {
if (type === BufferActionKind.AddBuffer) {
const buff = getBuffer(state, payload);
if (!buff) {
return {
activeIndex: state.buffers.length,
buffers: [
...state.buffers,
{
type: payload.toBuffer?.type!,
name: payload.toBuffer?.name!,
connection: payload.connection,
lines: [],
},
],
};
}
}
if (type === BufferActionKind.AddBufferLine && payload.message) {
const buff = getBuffer(state, payload);
if (buff) {
if (
!buff.lines.find(
(i) =>
payload.message?.time === i.time &&
payload.message.sender === i.sender,
)
) {
buff.lines = [...buff.lines, payload.message];
}
}
return { ...state };
}
if (type === BufferActionKind.UpdateNicklist) {
const channels = state.buffers.filter((buf) =>
buf.type === 'channel' && payload.channels?.length
? payload.channels.includes(buf.name)
: true,
);
channels.forEach((chanbuf) => {
const nicklist = payload.connection?.nicklist.getChannelByName(
chanbuf.name,
);
if (nicklist) {
chanbuf.nicks = nicklist.nicks;
}
});
return { ...state };
}
if (type === BufferActionKind.SetTopic && payload.topic) {
const buff = getBuffer(state, payload);
if (buff) {
buff.topic = payload.topic;
}
return { ...state };
}
}
if (
type === BufferActionKind.SetActiveBuffer &&
payload.activeIndex != null
) {
return {
...state,
activeIndex: payload.activeIndex,
};
}
return state;
};

52
src/lib/irc-manager.ts Normal file
View File

@ -0,0 +1,52 @@
import { IRCConnection, IRCNickList, TypedEventEmitter } from '@icynet/irclib';
import { IRCWebSocketConnector } from '@icynet/irclib/lib/connector/websocket.connector';
export interface IRCConnectionWrapper {
name: string;
connection: IRCConnection;
nicklist: IRCNickList;
}
export type ManagerEvents = {
connectionAdded: (connection: IRCConnectionWrapper) => void;
connectionRemoved: (connection: IRCConnectionWrapper) => void;
};
let connectionIndex = 0;
export class IRCManager extends TypedEventEmitter<ManagerEvents> {
public connections: IRCConnectionWrapper[] = [];
createNewConnection(
nick: string,
channels: string[],
host: string,
ssl = false,
port = 6667,
password?: string,
): IRCConnectionWrapper {
// TODO: validate inputs
const connection = new IRCConnection(
{
nick,
channels,
host,
ssl,
port,
password,
},
IRCWebSocketConnector,
);
const nicklist = new IRCNickList(connection);
const instance = {
name: `${nick}-${host}-${connectionIndex++}`,
connection,
nicklist,
};
this.connections.push(instance);
this.emit('connectionAdded', instance);
connection.connect();
return instance;
}
}

8
src/lib/utils/html.ts Normal file
View File

@ -0,0 +1,8 @@
export function escapeHtml(unsafe: string) {
return unsafe
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}

1
src/react-app-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

15
src/reportWebVitals.ts Normal file
View File

@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

5
src/setupTests.ts Normal file
View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

26
tsconfig.json Normal file
View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}