Files
outline/app/scenes/Document/components/SocketPresence.ts
忽如寄 9f400af73b refactor: ♻️ refactor isHosted && type clean up (#3290)
* refactor: ♻️ refactor isHosted && type clean up

Change-Id: I4dfbad8a07607432801de78920ce42bf81e46498

* refactor: ♻️ code clean up

Change-Id: I8f487a33d332a2acaff84397a97371b56ace28a1

* feat: 💄 lint

Change-Id: I776b1a5e249bdb542f8e6da7cb2277821cf91094

* feat:  ci type

Change-Id: I486dde7bf60321238e9a394c40ad8cdb8bfc54c8

* feat: some code sugession

Change-Id: I4761d057344b95a98e99068d312a42292977875b
2022-03-27 15:18:37 -07:00

83 lines
1.7 KiB
TypeScript

import * as React from "react";
import { USER_PRESENCE_INTERVAL } from "@shared/constants";
import { SocketContext } from "~/components/SocketProvider";
type Props = {
documentId: string;
isEditing: boolean;
};
export default class SocketPresence extends React.Component<Props> {
static contextType = SocketContext;
previousContext: typeof SocketContext;
editingInterval: ReturnType<typeof setInterval>;
componentDidMount() {
this.editingInterval = setInterval(() => {
if (this.props.isEditing) {
this.emitPresence();
}
}, USER_PRESENCE_INTERVAL);
this.setupOnce();
}
componentDidUpdate(prevProps: Props) {
this.setupOnce();
if (prevProps.isEditing !== this.props.isEditing) {
this.emitPresence();
}
}
componentWillUnmount() {
if (this.context) {
this.context.emit("leave", {
documentId: this.props.documentId,
});
this.context.off("authenticated", this.emitJoin);
}
clearInterval(this.editingInterval);
}
setupOnce = () => {
if (this.context && this.context !== this.previousContext) {
this.previousContext = this.context;
if (this.context.authenticated) {
this.emitJoin();
}
this.context.on("authenticated", () => {
this.emitJoin();
});
}
};
emitJoin = () => {
if (!this.context) {
return;
}
this.context.emit("join", {
documentId: this.props.documentId,
isEditing: this.props.isEditing,
});
};
emitPresence = () => {
if (!this.context) {
return;
}
this.context.emit("presence", {
documentId: this.props.documentId,
isEditing: this.props.isEditing,
});
};
render() {
return this.props.children || null;
}
}