Finish migrating user state over to MobX.

This commit is contained in:
Paul 2021-07-29 15:51:19 +01:00
parent 4dffaad6c1
commit f8611ddea5
11 changed files with 286 additions and 255 deletions

View file

@ -1,9 +1,13 @@
import { SYSTEM_USER_ID, User } from "revolt.js"; import { useStore } from "react-redux";
import { SYSTEM_USER_ID } from "revolt.js";
import { Channels } from "revolt.js/dist/api/objects"; import { Channels } from "revolt.js/dist/api/objects";
import styled, { css } from "styled-components"; import styled, { css } from "styled-components";
import { StateUpdater, useState } from "preact/hooks"; import { StateUpdater, useState } from "preact/hooks";
import { User } from "../../mobx";
import { useData } from "../../mobx/State";
import { useClient } from "../../context/revoltjs/RevoltClient"; import { useClient } from "../../context/revoltjs/RevoltClient";
import { emojiDictionary } from "../../assets/emojis"; import { emojiDictionary } from "../../assets/emojis";
@ -53,6 +57,7 @@ export function useAutoComplete(
const [state, setState] = useState<AutoCompleteState>({ type: "none" }); const [state, setState] = useState<AutoCompleteState>({ type: "none" });
const [focused, setFocused] = useState(false); const [focused, setFocused] = useState(false);
const client = useClient(); const client = useClient();
const store = useData();
function findSearchString( function findSearchString(
el: HTMLTextAreaElement, el: HTMLTextAreaElement,
@ -127,7 +132,7 @@ export function useAutoComplete(
let users: User[] = []; let users: User[] = [];
switch (searchClues.users.type) { switch (searchClues.users.type) {
case "all": case "all":
users = client.users.toArray(); users = [...store.users.values()];
break; break;
case "channel": { case "channel": {
const channel = client.channels.get( const channel = client.channels.get(
@ -136,8 +141,8 @@ export function useAutoComplete(
switch (channel?.channel_type) { switch (channel?.channel_type) {
case "Group": case "Group":
case "DirectMessage": case "DirectMessage":
users = client.users users = channel.recipients
.mapKeys(channel.recipients) .map((x) => store.users.get(x))
.filter( .filter(
(x) => typeof x !== "undefined", (x) => typeof x !== "undefined",
) as User[]; ) as User[];
@ -150,7 +155,7 @@ export function useAutoComplete(
(x) => x._id.substr(0, 26) === server, (x) => x._id.substr(0, 26) === server,
) )
.map((x) => .map((x) =>
client.users.get(x._id.substr(26)), store.users.get(x._id.substr(26)),
) )
.filter( .filter(
(x) => typeof x !== "undefined", (x) => typeof x !== "undefined",

View file

@ -1,7 +1,10 @@
import { observer } from "mobx-react-lite";
import { attachContextMenu } from "preact-context-menu"; import { attachContextMenu } from "preact-context-menu";
import { memo } from "preact/compat"; import { memo } from "preact/compat";
import { useContext, useState } from "preact/hooks"; import { useContext, useState } from "preact/hooks";
import { useData } from "../../../mobx/State";
import { QueuedMessage } from "../../../redux/reducers/queue"; import { QueuedMessage } from "../../../redux/reducers/queue";
import { useIntermediate } from "../../../context/intermediate/Intermediate"; import { useIntermediate } from "../../../context/intermediate/Intermediate";
@ -34,7 +37,8 @@ interface Props {
head?: boolean; head?: boolean;
} }
function Message({ const Message = observer(
({
highlight, highlight,
attachContext, attachContext,
message, message,
@ -42,15 +46,16 @@ function Message({
content: replacement, content: replacement,
head: preferHead, head: preferHead,
queued, queued,
}: Props) { }: Props) => {
// TODO: Can improve re-renders here by providing a list const store = useData();
// TODO: of dependencies. We only need to update on u/avatar. const user = store.users.get(message.author);
const user = useUser(message.author);
const client = useContext(AppContext); const client = useContext(AppContext);
const { openScreen } = useIntermediate(); const { openScreen } = useIntermediate();
const content = message.content as string; const content = message.content as string;
const head = preferHead || (message.replies && message.replies.length > 0); const head =
preferHead || (message.replies && message.replies.length > 0);
// ! FIXME: tell fatal to make this type generic // ! FIXME: tell fatal to make this type generic
// bree: Fatal please... // bree: Fatal please...
@ -78,7 +83,9 @@ function Message({
))} ))}
<MessageBase <MessageBase
highlight={highlight} highlight={highlight}
head={head && !(message.replies && message.replies.length > 0)} head={
head && !(message.replies && message.replies.length > 0)
}
contrast={contrast} contrast={contrast}
sending={typeof queued !== "undefined"} sending={typeof queued !== "undefined"}
mention={message.mentions?.includes(client.user!._id)} mention={message.mentions?.includes(client.user!._id)}
@ -116,7 +123,10 @@ function Message({
onContextMenu={userContext} onContextMenu={userContext}
onClick={openProfile} onClick={openProfile}
/> />
<MessageDetail message={message} position="top" /> <MessageDetail
message={message}
position="top"
/>
</span> </span>
)} )}
{replacement ?? <Markdown content={content} />} {replacement ?? <Markdown content={content} />}
@ -137,6 +147,7 @@ function Message({
</MessageBase> </MessageBase>
</div> </div>
); );
} },
);
export default memo(Message); export default memo(Message);

View file

@ -1,10 +1,13 @@
import { User } from "revolt.js"; import { observer } from "mobx-react-lite";
import styled from "styled-components"; import styled from "styled-components";
import { attachContextMenu } from "preact-context-menu"; import { attachContextMenu } from "preact-context-menu";
import { TextReact } from "../../../lib/i18n"; import { TextReact } from "../../../lib/i18n";
import { User } from "../../../mobx";
import { useData } from "../../../mobx/State";
import { useForceUpdate, useUser } from "../../../context/revoltjs/hooks"; import { useForceUpdate, useUser } from "../../../context/revoltjs/hooks";
import { MessageObject } from "../../../context/revoltjs/util"; import { MessageObject } from "../../../context/revoltjs/util";
@ -39,13 +42,9 @@ interface Props {
hideInfo?: boolean; hideInfo?: boolean;
} }
export function SystemMessage({ export const SystemMessage = observer(
attachContext, ({ attachContext, message, highlight, hideInfo }: Props) => {
message, const store = useData();
highlight,
hideInfo,
}: Props) {
const ctx = useForceUpdate();
let data: SystemMessageParsed; let data: SystemMessageParsed;
const content = message.content; const content = message.content;
@ -58,8 +57,8 @@ export function SystemMessage({
case "user_remove": case "user_remove":
data = { data = {
type: content.type, type: content.type,
user: useUser(content.id, ctx) as User, user: store.users.get(content.id)!,
by: useUser(content.by, ctx) as User, by: store.users.get(content.by)!,
}; };
break; break;
case "user_joined": case "user_joined":
@ -68,21 +67,21 @@ export function SystemMessage({
case "user_banned": case "user_banned":
data = { data = {
type: content.type, type: content.type,
user: useUser(content.id, ctx) as User, user: store.users.get(content.id)!,
}; };
break; break;
case "channel_renamed": case "channel_renamed":
data = { data = {
type: "channel_renamed", type: "channel_renamed",
name: content.name, name: content.name,
by: useUser(content.by, ctx) as User, by: store.users.get(content.by)!,
}; };
break; break;
case "channel_description_changed": case "channel_description_changed":
case "channel_icon_changed": case "channel_icon_changed":
data = { data = {
type: content.type, type: content.type,
by: useUser(content.by, ctx) as User, by: store.users.get(content.by)!,
}; };
break; break;
default: default:
@ -102,7 +101,9 @@ export function SystemMessage({
children = ( children = (
<TextReact <TextReact
id={`app.main.channel.system.${ id={`app.main.channel.system.${
data.type === "user_added" ? "added_by" : "removed_by" data.type === "user_added"
? "added_by"
: "removed_by"
}`} }`}
fields={{ fields={{
user: <UserShort user={data.user} />, user: <UserShort user={data.user} />,
@ -167,4 +168,5 @@ export function SystemMessage({
<SystemContent>{children}</SystemContent> <SystemContent>{children}</SystemContent>
</MessageBase> </MessageBase>
); );
} },
);

View file

@ -1,5 +1,6 @@
import { Reply } from "@styled-icons/boxicons-regular"; import { Reply } from "@styled-icons/boxicons-regular";
import { File } from "@styled-icons/boxicons-solid"; import { File } from "@styled-icons/boxicons-solid";
import { observer } from "mobx-react-lite";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import { SYSTEM_USER_ID } from "revolt.js"; import { SYSTEM_USER_ID } from "revolt.js";
import { Users } from "revolt.js/dist/api/objects"; import { Users } from "revolt.js/dist/api/objects";
@ -10,6 +11,8 @@ import { useLayoutEffect, useState } from "preact/hooks";
import { useRenderState } from "../../../../lib/renderer/Singleton"; import { useRenderState } from "../../../../lib/renderer/Singleton";
import { useData } from "../../../../mobx/State";
import { useForceUpdate, useUser } from "../../../../context/revoltjs/hooks"; import { useForceUpdate, useUser } from "../../../../context/revoltjs/hooks";
import { mapMessage, MessageObject } from "../../../../context/revoltjs/util"; import { mapMessage, MessageObject } from "../../../../context/revoltjs/util";
@ -120,7 +123,7 @@ export const ReplyBase = styled.div<{
`} `}
`; `;
export function MessageReply({ index, channel, id }: Props) { export const MessageReply = observer(({ index, channel, id }: Props) => {
const ctx = useForceUpdate(); const ctx = useForceUpdate();
const view = useRenderState(channel); const view = useRenderState(channel);
if (view?.type !== "RENDER") return null; if (view?.type !== "RENDER") return null;
@ -152,7 +155,8 @@ export function MessageReply({ index, channel, id }: Props) {
); );
} }
const user = useUser(message.author, ctx); const store = useData();
const user = store.users.get(message.author);
const history = useHistory(); const history = useHistory();
return ( return (
@ -203,4 +207,4 @@ export function MessageReply({ index, channel, id }: Props) {
)} )}
</ReplyBase> </ReplyBase>
); );
} });

View file

@ -4,6 +4,7 @@ import {
File, File,
XCircle, XCircle,
} from "@styled-icons/boxicons-regular"; } from "@styled-icons/boxicons-regular";
import { observer } from "mobx-react-lite";
import { SYSTEM_USER_ID } from "revolt.js"; import { SYSTEM_USER_ID } from "revolt.js";
import styled from "styled-components"; import styled from "styled-components";
@ -13,6 +14,7 @@ import { StateUpdater, useEffect } from "preact/hooks";
import { internalSubscribe } from "../../../../lib/eventEmitter"; import { internalSubscribe } from "../../../../lib/eventEmitter";
import { useRenderState } from "../../../../lib/renderer/Singleton"; import { useRenderState } from "../../../../lib/renderer/Singleton";
import { useData } from "../../../../mobx/State";
import { Reply } from "../../../../redux/reducers/queue"; import { Reply } from "../../../../redux/reducers/queue";
import { useUsers } from "../../../../context/revoltjs/hooks"; import { useUsers } from "../../../../context/revoltjs/hooks";
@ -56,7 +58,7 @@ const Base = styled.div`
// ! FIXME: Move to global config // ! FIXME: Move to global config
const MAX_REPLIES = 5; const MAX_REPLIES = 5;
export default function ReplyBar({ channel, replies, setReplies }: Props) { export default observer(({ channel, replies, setReplies }: Props) => {
useEffect(() => { useEffect(() => {
return internalSubscribe( return internalSubscribe(
"ReplyBar", "ReplyBar",
@ -73,7 +75,9 @@ export default function ReplyBar({ channel, replies, setReplies }: Props) {
const ids = replies.map((x) => x.id); const ids = replies.map((x) => x.id);
const messages = view.messages.filter((x) => ids.includes(x._id)); const messages = view.messages.filter((x) => ids.includes(x._id));
const users = useUsers(messages.map((x) => x.author));
const store = useData();
const users = messages.map((x) => store.users.get(x.author));
return ( return (
<div> <div>
@ -90,9 +94,7 @@ export default function ReplyBar({ channel, replies, setReplies }: Props) {
</span> </span>
); );
const user = users.find((x) => message!.author === x?._id); const user = users[index];
if (!user) return;
return ( return (
<Base key={reply.id}> <Base key={reply.id}>
<ReplyBase preview> <ReplyBase preview>
@ -143,4 +145,4 @@ export default function ReplyBar({ channel, replies, setReplies }: Props) {
})} })}
</div> </div>
); );
} });

View file

@ -1,3 +1,4 @@
import { observer } from "mobx-react-lite";
import { User } from "revolt.js"; import { User } from "revolt.js";
import styled from "styled-components"; import styled from "styled-components";
@ -6,10 +7,14 @@ import { useContext } from "preact/hooks";
import { TextReact } from "../../../../lib/i18n"; import { TextReact } from "../../../../lib/i18n";
import { useData } from "../../../../mobx/State";
import { connectState } from "../../../../redux/connector"; import { connectState } from "../../../../redux/connector";
import { TypingUser } from "../../../../redux/reducers/typing"; import { TypingUser } from "../../../../redux/reducers/typing";
import { AppContext } from "../../../../context/revoltjs/RevoltClient"; import {
AppContext,
useClient,
} from "../../../../context/revoltjs/RevoltClient";
import { useUsers } from "../../../../context/revoltjs/hooks"; import { useUsers } from "../../../../context/revoltjs/hooks";
import { Username } from "../../user/UserShort"; import { Username } from "../../user/UserShort";
@ -61,12 +66,13 @@ const Base = styled.div`
} }
`; `;
export function TypingIndicator({ typing }: Props) { export const TypingIndicator = observer(({ typing }: Props) => {
if (typing && typing.length > 0) { if (typing && typing.length > 0) {
const client = useContext(AppContext); const client = useClient();
const users = useUsers(typing.map((x) => x.id)).filter( const store = useData();
(x) => typeof x !== "undefined", const users = typing
) as User[]; .map((x) => store.users.get(x.id)!)
.filter((x) => typeof x !== "undefined");
users.sort((a, b) => users.sort((a, b) =>
a._id.toUpperCase().localeCompare(b._id.toUpperCase()), a._id.toUpperCase().localeCompare(b._id.toUpperCase()),
@ -123,7 +129,7 @@ export function TypingIndicator({ typing }: Props) {
} }
return null; return null;
} });
export default connectState<{ id: string }>(TypingIndicator, (state, props) => { export default connectState<{ id: string }>(TypingIndicator, (state, props) => {
return { return {

View file

@ -1,8 +1,9 @@
import { User } from "revolt.js"; import { User } from "../../../mobx";
import Checkbox, { CheckboxProps } from "../../ui/Checkbox"; import Checkbox, { CheckboxProps } from "../../ui/Checkbox";
import UserIcon from "./UserIcon"; import UserIcon from "./UserIcon";
import { Username } from "./UserShort";
type UserProps = Omit<CheckboxProps, "children"> & { user: User }; type UserProps = Omit<CheckboxProps, "children"> & { user: User };
@ -10,7 +11,7 @@ export default function UserCheckbox({ user, ...props }: UserProps) {
return ( return (
<Checkbox {...props}> <Checkbox {...props}>
<UserIcon target={user} size={32} /> <UserIcon target={user} size={32} />
{user.username} <Username user={user} />
</Checkbox> </Checkbox>
); );
} }

View file

@ -1,6 +1,6 @@
import { Cog } from "@styled-icons/boxicons-solid"; import { Cog } from "@styled-icons/boxicons-solid";
import { observer } from "mobx-react-lite";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { User } from "revolt.js";
import styled from "styled-components"; import styled from "styled-components";
import { openContextMenu } from "preact-context-menu"; import { openContextMenu } from "preact-context-menu";
@ -9,6 +9,8 @@ import { Localizer } from "preact-i18n";
import { isTouchscreenDevice } from "../../../lib/isTouchscreenDevice"; import { isTouchscreenDevice } from "../../../lib/isTouchscreenDevice";
import { User } from "../../../mobx";
import { useIntermediate } from "../../../context/intermediate/Intermediate"; import { useIntermediate } from "../../../context/intermediate/Intermediate";
import Header from "../../ui/Header"; import Header from "../../ui/Header";
@ -49,7 +51,7 @@ interface Props {
user: User; user: User;
} }
export default function UserHeader({ user }: Props) { export default observer(({ user }: Props) => {
const { writeClipboard } = useIntermediate(); const { writeClipboard } = useIntermediate();
return ( return (
@ -81,4 +83,4 @@ export default function UserHeader({ user }: Props) {
)} )}
</Header> </Header>
); );
} });

View file

@ -21,7 +21,7 @@ export const Username = observer(
let username = user?.username; let username = user?.username;
let color; let color;
// ! FIXME: this must be really bad for perf. /* // ! FIXME: this must be really bad for perf.
if (user) { if (user) {
let { server } = useParams<{ server?: string }>(); let { server } = useParams<{ server?: string }>();
if (server) { if (server) {
@ -44,7 +44,7 @@ export const Username = observer(
} }
} }
} }
} } */
return ( return (
<span {...otherProps} style={{ color }}> <span {...otherProps} style={{ color }}>

View file

@ -1,14 +1,16 @@
import { Search } from "@styled-icons/boxicons-regular"; import { Search } from "@styled-icons/boxicons-regular";
import { Message, Group, Inbox } from "@styled-icons/boxicons-solid"; import { Message, Group, Inbox } from "@styled-icons/boxicons-solid";
import { observer } from "mobx-react-lite";
import { useHistory, useLocation } from "react-router"; import { useHistory, useLocation } from "react-router";
import styled, { css } from "styled-components"; import styled, { css } from "styled-components";
import ConditionalLink from "../../lib/ConditionalLink"; import ConditionalLink from "../../lib/ConditionalLink";
import { useData } from "../../mobx/State";
import { connectState } from "../../redux/connector"; import { connectState } from "../../redux/connector";
import { LastOpened } from "../../redux/reducers/last_opened"; import { LastOpened } from "../../redux/reducers/last_opened";
import { useSelf } from "../../context/revoltjs/hooks"; import { useClient } from "../../context/revoltjs/RevoltClient";
import UserIcon from "../common/user/UserIcon"; import UserIcon from "../common/user/UserIcon";
import IconButton from "../ui/IconButton"; import IconButton from "../ui/IconButton";
@ -51,8 +53,11 @@ interface Props {
lastOpened: LastOpened; lastOpened: LastOpened;
} }
export function BottomNavigation({ lastOpened }: Props) { export const BottomNavigation = observer(({ lastOpened }: Props) => {
const user = useSelf(); const client = useClient();
const store = useData();
const user = store.users.get(client.user!._id);
const history = useHistory(); const history = useHistory();
const path = useLocation().pathname; const path = useLocation().pathname;
@ -114,7 +119,7 @@ export function BottomNavigation({ lastOpened }: Props) {
</Navbar> </Navbar>
</Base> </Base>
); );
} });
export default connectState(BottomNavigation, (state) => { export default connectState(BottomNavigation, (state) => {
return { return {

View file

@ -1,14 +1,14 @@
import { User, Users } from "revolt.js/dist/api/objects"; import { Users } from "revolt.js/dist/api/objects";
import styles from "./UserPicker.module.scss"; import styles from "./UserPicker.module.scss";
import { Text } from "preact-i18n"; import { Text } from "preact-i18n";
import { useState } from "preact/hooks"; import { useState } from "preact/hooks";
import { useData } from "../../../mobx/State";
import UserCheckbox from "../../../components/common/user/UserCheckbox"; import UserCheckbox from "../../../components/common/user/UserCheckbox";
import Modal from "../../../components/ui/Modal"; import Modal from "../../../components/ui/Modal";
import { useUsers } from "../../revoltjs/hooks";
interface Props { interface Props {
omit?: string[]; omit?: string[];
onClose: () => void; onClose: () => void;
@ -19,7 +19,7 @@ export function UserPicker(props: Props) {
const [selected, setSelected] = useState<string[]>([]); const [selected, setSelected] = useState<string[]>([]);
const omit = [...(props.omit || []), "00000000000000000000000000"]; const omit = [...(props.omit || []), "00000000000000000000000000"];
const users = useUsers(); const store = useData();
return ( return (
<Modal <Modal
@ -33,24 +33,17 @@ export function UserPicker(props: Props) {
}, },
]}> ]}>
<div className={styles.list}> <div className={styles.list}>
{( {[...store.users.values()]
users.filter( .filter(
(x) => (x) =>
x && x &&
x.relationship === Users.Relationship.Friend && x.relationship === Users.Relationship.Friend &&
!omit.includes(x._id), !omit.includes(x._id),
) as User[]
) )
.map((x) => {
return {
...x,
selected: selected.includes(x._id),
};
})
.map((x) => ( .map((x) => (
<UserCheckbox <UserCheckbox
user={x} user={x}
checked={x.selected} checked={selected.includes(x._id)}
onChange={(v) => { onChange={(v) => {
if (v) { if (v) {
setSelected([...selected, x._id]); setSelected([...selected, x._id]);