Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] typing indicator #66

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions api/channels-list/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import "../startup";
import { Context, HttpRequest } from "@azure/functions";
import { authorized } from "../common/ApiRequestContext";

type ChannelSummary = { name: string };
type ChannelSummary = { name: string; type: string };
type ChannelListResponse = { channels: ChannelSummary[] };

export default async function (context: Context, req: HttpRequest): Promise<void> {
await authorized(context, req, () => {
const channels: ChannelListResponse = {
channels: [{ name: "global-welcome" }, { name: "some-other-channel" }]
channels: [
{ name: "global-welcome", type: "public" },
{ name: "some-other-channel", type: "public" },
{ name: "utility", type: "private" }
]
};

context.res = { status: 200, body: JSON.stringify(channels) };
Expand Down
10 changes: 7 additions & 3 deletions app/src/components/Channels/ChannelBrowser.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@ import ChatContainer from "../Chat/ChatContainer";
export default function ({ toggleChannelView }) {
const { api } = useAuth();
const [channels, setChannels] = useState([]);
const [currentChannel, setCurrentChannel] = useState("global-welcome");
const [currentChannel, setCurrentChannel] = useState(null);

const [] = useState("");

useEffect(() => {
const fetchChannels = async () => {
const response = await api.listChannels();
setChannels(response.channels);
const { channels } = response;
setChannels(channels);
setCurrentChannel(channels[0].name);
};
fetchChannels();
}, []);
Expand All @@ -23,7 +27,7 @@ export default function ({ toggleChannelView }) {
toggleChannelView();
};

return (
return !currentChannel ? null : (
<>
<ChannelList channels={channels} onChannelSelected={channelSelected} />
<ChatContainer currentChannel={currentChannel} onChatExit={toggleChannelView} />
Expand Down
3 changes: 2 additions & 1 deletion app/src/components/Channels/ChannelList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ const ChannelList = ({ channels, onChannelSelected }) => {
onChannelSelected(channel.name);
};

const channelListItems = channels.map((channel) => (
const publicChannels = channels.filter((el) => el.type === "public");
const channelListItems = publicChannels.map((channel) => (
<li key={channel.name}>
<Link
to={`/channel/${channel.name}`}
Expand Down
69 changes: 61 additions & 8 deletions app/src/components/Chat/ChatContainer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,76 @@ import useArchive from "./../../hooks/useArchive";
import autoScrollHistory from "./autoScrollHistory";
import "./chat.css";

const ChatInputStatus = ({ message }) => {
return <div className="send-status">{message}</div>;
};

const formatMessage = (eventObject) => {
// coerse String to Object
return typeof eventObject === "string" //
? { text: `${eventObject || ""}`.trim() }
: eventObject;
};

const ChatContainer = ({ currentChannel, onChatExit }) => {
const endOfChatLog = useRef(null);
const [archive, rewind] = useArchive(currentChannel);

const [history, setHistory] = useState([]);
const [status, setStatus] = useState([]);
const [activity, setActivity] = useState();

useEffect(() => {
setHistory([]); // Reset history on channel change
}, [currentChannel]);
// Reset history on channel change

const [channel] = useChannel(currentChannel, (message) => {
setHistory((prev) => [...prev.slice(-199), message]);
});

const [archive, rewind] = useArchive(currentChannel);
const sendMessage = (eventObject = null) => {
channel.publish("message", formatMessage(eventObject));
setStatusMessage(null);
};

const sendMessage = (messageText) => {
channel.publish("message", { text: messageText });
const sendStatus = (eventObject = null) => {
channel.presence.enter();
channel.presence.update(formatMessage(eventObject));
};

const handlePresenceUpdate = (member) => {
const { data, clientId, connectionId } = member;
const { text } = data;

if (text === activity) return;

// clients on channel excluding the author as shallow copy Object
let clients = [];

channel.presence.get((_, members) => {
const typing = clientId === member.clientId;
Copy link

@cruickshankpg cruickshankpg Apr 25, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isn't this always going to be true? clientId was defined on line 45 from member and you're then just comparing it back on itself again

clients = members.map((client) => ({ ...client, typing }));
console.log(typing, clientId, member.clientId);
});

switch (text) {
case "start":
console.log(text);
setActivity("Typing ...");
break;

case "done":
console.log(text);
setActivity("");
break;

default:
break;
}
};

useEffect(() => setHistory([]), [currentChannel]);
useEffect(() => setStatus(activity), [activity]);
useEffect(() => channel.presence.subscribe(handlePresenceUpdate));

autoScrollHistory(archive, endOfChatLog);

return (
Expand All @@ -42,8 +94,9 @@ const ChatContainer = ({ currentChannel, onChatExit }) => {
<ChatList history={history} />
<li className="end-message" ref={endOfChatLog} />
</ul>
<ChatInput sendMessage={sendMessage} />
</section >
<ChatInput sendMessage={sendMessage} sendStatus={sendStatus} />
<ChatInputStatus message={status} />
</section>
);
};

Expand Down
60 changes: 42 additions & 18 deletions app/src/components/Chat/ChatInput.jsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,57 @@
import React from "react";
import ContentEditable from "react-contenteditable";

export const ChatInput = ({ sendMessage }) => {
let timer = -1;

export const ChatInput = ({ sendMessage, sendStatus }) => {
const [message, setMessage] = React.useState("");
const clearStatusAfter = 5 * 1000; // miliseconds

React.useEffect(() => {
if (!message) return;
if (timer < 0) sendStatus("start");

const callback = () => {
sendStatus("done");
console.log({ timer });
timer = -1;
};

clearTimeout(timer);
timer = setTimeout(callback, clearStatusAfter);
}, [message]);

const handleSubmit = (e) => {
e.preventDefault();
if (message.trim() === "") {
return;
}
if (!`${message}`.trim()) return;

sendMessage(message);
setMessage("");
clearTimeout(timer);
timer = -1;
sendStatus("done");
};

const handleChange = ({ target }) => setMessage(target.value || "");

const handleKeydown = (e) => {
const passive = /^(control|arrow|shift|alt|meta|page|insert|home)/i;
if (passive.test(e.code)) return;

switch (e.code) {
case "Enter":
handleSubmit(e);
break;

default:
// tarpit for keypress
break;
}
};

return (
<form className="send" onSubmit={handleSubmit}>
<textarea
autoFocus
className="send-input"
onChange={(e) => {
setMessage(e.target.value);
}}
onKeyDown={(e) => {
if (e.code == "Enter") {
e.preventDefault();
handleSubmit(e);
}
}}
value={message}
></textarea>
<ContentEditable className="send-message" html={ message } onChange={handleChange} onKeyDown={handleKeydown} />
<button className="send-button">Send</button>
</form>
);
Expand Down
23 changes: 16 additions & 7 deletions app/src/components/Chat/chat.css
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,31 @@

.send {
display: flex;
margin: 0 1rem 1rem;
flex-direction: row;
margin: 0 0.5rem;
font-size: 1rem;
}

.send-input {
.send-status {
color: #777777;
font-size: 0.8rem;
height: 1.5rem;
margin: 0.25rem 0.5rem 0;
}

.send-input,
.send-message {
width: 100%;
padding: var(--spacer);
font-size: 1rem;
font-family: inherit;
border: 1px solid black;
border-radius: 0;
}

.send-button {
padding: 1rem 2rem;
padding: 0.5rem 1rem;
border: 0;
font-family: inherit;
font-size: 1rem;
font-weight: bold;
font-family: inherit;
background-color: var(--primary);
color: var(--primary-text);
cursor: pointer;
Expand Down
40 changes: 24 additions & 16 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"ansi-regex": "^5.0.1",
"prop-types": "^15.7.2",
"react": "^17.0.2",
"react-contenteditable": "^3.3.6",
"react-dom": "^17.0.2",
"react-router-dom": "^5.3.0",
"tslib": "^2.3.1"
Expand Down