Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 595f7c3888 | |||
|
825be4eb33 |
|||
|
1c90a0c859 |
|||
| 6dee7e8dcc | |||
| 41258a8483 |
31 changed files with 574 additions and 326 deletions
|
|
@ -22,9 +22,9 @@ tauri-plugin-opener = "2"
|
|||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
base64 = "0.22"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||
reqwest = { version = "0.13", default-features = false, features = ["json", "rustls-tls"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "sync", "time"] }
|
||||
mtp = { git = "https://git.methanium.net/methanium/mtp.git", rev = "7182272e3edb0079d7b74b45b2f62a298d2fee22", features = ["client", "crypto"] }
|
||||
mtp = { git = "https://git.methanium.net/methanium/mtp.git", rev = "b067614a684eb1856bc5db7b3fd82148c036ce6b", features = ["client", "crypto"] }
|
||||
mtp-transport = { git = "https://git.methanium.net/methanium/mtp.git", rev = "b067614a684eb1856bc5db7b3fd82148c036ce6b" }
|
||||
webpki-root-certs = "1"
|
||||
tauri-plugin-deep-link = "2"
|
||||
|
|
|
|||
|
|
@ -15,7 +15,10 @@ export function Basic({
|
|||
user,
|
||||
extra,
|
||||
}: {
|
||||
user: User;
|
||||
user: Pick<
|
||||
User,
|
||||
"Display" | "Username" | "Avatar" | "OnlineStatus" | "Status"
|
||||
>;
|
||||
extra?: React.ReactNode;
|
||||
}) {
|
||||
const display = user.Display || user.Username || "Unknown";
|
||||
|
|
@ -57,8 +60,9 @@ export function Basic({
|
|||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-start justify-center gap-1 text-[15px]">
|
||||
<div className="flex w-full flex-col items-start justify-center text-[15px]">
|
||||
<p>{display}</p>
|
||||
<p className="text-xs text-muted-foreground">{user.Status}</p>
|
||||
</div>
|
||||
<div className="pr-1">{extra}</div>
|
||||
</Button>
|
||||
|
|
|
|||
|
|
@ -4,7 +4,20 @@ import { Text } from "@methanium/ui/markdown";
|
|||
import { ChevronDown, ChevronUp } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
export default function Profile({ user }: { user: User }) {
|
||||
export default function Profile({
|
||||
user,
|
||||
}: {
|
||||
user: Pick<
|
||||
User,
|
||||
| "UserId"
|
||||
| "Display"
|
||||
| "Username"
|
||||
| "Avatar"
|
||||
| "About"
|
||||
| "IotaId"
|
||||
| "PublicKey"
|
||||
>;
|
||||
}) {
|
||||
const [showAdvancedInformation, setShowAdvancedInformation] = useState(false);
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -91,6 +91,15 @@ export default function Navbar({ forMobile }: { forMobile: boolean }) {
|
|||
{pathname === "/chat" && id && (
|
||||
<Wrapper
|
||||
userId={id}
|
||||
fields={[
|
||||
"UserId",
|
||||
"Display",
|
||||
"Username",
|
||||
"Avatar",
|
||||
"About",
|
||||
"IotaId",
|
||||
"PublicKey",
|
||||
]}
|
||||
component={(user) =>
|
||||
isMobile ? (
|
||||
<p className="font-medium text-[1.07rem]">{user?.Display}</p>
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ import SidebarBox from "@tensamin/call/sidebarBox";
|
|||
import { useShowMobileNavbar } from "@/routes/app/useShowMobileNavbar";
|
||||
import { Ellipsis, Check } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import type { User } from "@tensamin/user/context";
|
||||
import { useUser, type User } from "@tensamin/user/context";
|
||||
import { mtp, userPresencePreferenceSchema } from "@tensamin/shared/data";
|
||||
import { useMTP } from "@tensamin/mtp";
|
||||
import {
|
||||
|
|
@ -64,7 +64,7 @@ function StatusDialog({
|
|||
saveSucceeded,
|
||||
setSaveSucceeded,
|
||||
}: {
|
||||
user: User;
|
||||
user: Pick<User, "UserId" | "OnlineStatus" | "Status">;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
send: ReturnType<typeof useMTP>["send"];
|
||||
|
|
@ -77,6 +77,8 @@ function StatusDialog({
|
|||
saveSucceeded: boolean;
|
||||
setSaveSucceeded: (value: boolean) => void;
|
||||
}) {
|
||||
const { updateProfile, updateState } = useUser();
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
|
|
@ -137,9 +139,10 @@ function StatusDialog({
|
|||
<DialogClose render={<Button variant="destructive">Cancel</Button>} />
|
||||
<Button
|
||||
onClick={async () => {
|
||||
const payload = { UserState: draftOnlineStatus };
|
||||
|
||||
const validation = mtp.SetUserState.request.safeParse(payload);
|
||||
const validation = mtp.ChangeUserData.request.safeParse({
|
||||
OnlineStatus: draftOnlineStatus,
|
||||
Status: draftStatus,
|
||||
});
|
||||
|
||||
if (!validation.success) {
|
||||
setSaveSucceeded(false);
|
||||
|
|
@ -150,17 +153,9 @@ function StatusDialog({
|
|||
}
|
||||
|
||||
try {
|
||||
await send("SetUserState", validation.data);
|
||||
const profileValidation = mtp.ChangeUserData.request.safeParse({
|
||||
Status: draftStatus,
|
||||
});
|
||||
if (!profileValidation.success) {
|
||||
throw new Error(
|
||||
profileValidation.error.issues[0]?.message ??
|
||||
"Invalid status data",
|
||||
);
|
||||
}
|
||||
await send("ChangeUserData", profileValidation.data);
|
||||
await send("ChangeUserData", validation.data);
|
||||
updateState(user.UserId, draftOnlineStatus);
|
||||
await updateProfile(user.UserId, { Status: draftStatus });
|
||||
setSaveSucceeded(true);
|
||||
setErrorMessage("");
|
||||
} catch (err) {
|
||||
|
|
@ -209,6 +204,14 @@ export default function Sidebar() {
|
|||
<Wrapper
|
||||
loading={<Loading />}
|
||||
userId={"own"}
|
||||
fields={[
|
||||
"UserId",
|
||||
"Display",
|
||||
"Username",
|
||||
"Avatar",
|
||||
"OnlineStatus",
|
||||
"Status",
|
||||
]}
|
||||
component={(user) => (
|
||||
<>
|
||||
<Basic
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ export const onlineStatusOptions = [
|
|||
{ label: "Online", value: "user_online" },
|
||||
{ label: "Idle", value: "user_idle" },
|
||||
{ label: "Do not disturb", value: "user_dnd" },
|
||||
{ label: "Away", value: "user_wc" },
|
||||
{ label: "On the toilet", value: "user_wc" },
|
||||
{ label: "Offline", value: "user_invisible" },
|
||||
] as const;
|
||||
|
||||
|
|
|
|||
|
|
@ -28,6 +28,13 @@ export default function ConversationModal({ userId }: { userId: number }) {
|
|||
<Wrapper
|
||||
loading={<Loading />}
|
||||
userId={userId}
|
||||
fields={[
|
||||
"Display",
|
||||
"Username",
|
||||
"Avatar",
|
||||
"OnlineStatus",
|
||||
"Status",
|
||||
]}
|
||||
component={(user) => <Basic user={user} />}
|
||||
/>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -63,6 +63,7 @@ export default function InviteButton({
|
|||
<Wrapper
|
||||
key={contact.UserId}
|
||||
userId={contact.UserId}
|
||||
fields={["Display"]}
|
||||
loading={<div>Loading...</div>}
|
||||
component={(user) => (
|
||||
<Button
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ export default function InvitePopup({
|
|||
return (
|
||||
<Wrapper
|
||||
userId={user}
|
||||
fields={["Avatar", "Display"]}
|
||||
loading={null}
|
||||
component={(user) => (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
|
|
|
|||
|
|
@ -16,13 +16,15 @@ import {
|
|||
} from "../../store";
|
||||
import { Track, type Participant } from "livekit-client";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useUser, type User } from "@tensamin/user/context";
|
||||
import { type SelectedUser, useUserFields } from "@tensamin/user/context";
|
||||
import { useIsSpeaking } from "../../speakingState";
|
||||
import VideoViewer from "../videoViewer";
|
||||
import { HeadphoneOff, MicOff, Monitor, Plus, Shield } from "lucide-react";
|
||||
import ContextMenu from "./contextMenu";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
|
||||
const USER_FIELDS = ["UserId", "Avatar", "Display"] as const;
|
||||
|
||||
function getTrackPublicationBySource(
|
||||
participant: Participant | undefined,
|
||||
source: Track.Source,
|
||||
|
|
@ -113,7 +115,7 @@ function Overlay({
|
|||
participant,
|
||||
}: {
|
||||
type: "user" | "stream";
|
||||
user: User;
|
||||
user: SelectedUser<typeof USER_FIELDS>;
|
||||
participant: Participant;
|
||||
}) {
|
||||
const isAdmin = getRoomMetadata()?.admins.includes(user.UserId) === true;
|
||||
|
|
@ -163,12 +165,16 @@ export default function Base({
|
|||
fill?: boolean;
|
||||
flush?: boolean;
|
||||
}) {
|
||||
const { get } = useUser();
|
||||
const { load } = useStorage();
|
||||
|
||||
const focusedParticipantId = useCall((state) => state.focusedParticipantId);
|
||||
const view = useCall((state) => state.view);
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const participantId = Number(participant?.identity);
|
||||
const validParticipantId =
|
||||
participant && Number.isInteger(participantId) && participantId > 0
|
||||
? participantId
|
||||
: null;
|
||||
const { data: user } = useUserFields(validParticipantId, USER_FIELDS);
|
||||
const [avatarBackgroundColor, setAvatarBackgroundColor] = useState<
|
||||
string | undefined
|
||||
>(undefined);
|
||||
|
|
@ -191,31 +197,6 @@ export default function Base({
|
|||
load("user_id").then(setOwnId);
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
const participantId = Number(participant?.identity);
|
||||
|
||||
if (
|
||||
!participant ||
|
||||
!Number.isInteger(participantId) ||
|
||||
participantId <= 0
|
||||
) {
|
||||
setUser(null);
|
||||
return;
|
||||
}
|
||||
|
||||
let active = true;
|
||||
|
||||
void get(participantId).then((nextUser) => {
|
||||
if (active) {
|
||||
setUser(nextUser);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [participant, get]);
|
||||
|
||||
useEffect(() => {
|
||||
if (type !== "user" || !user?.Avatar) {
|
||||
setAvatarBackgroundColor(undefined);
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import {
|
|||
ContextMenuSeparator,
|
||||
Slider,
|
||||
} from "@methanium/ui";
|
||||
import type { User } from "@tensamin/user/context";
|
||||
import { setParticipantCameraDisabled, useCall } from "../../store";
|
||||
import { useState } from "react";
|
||||
|
||||
|
|
@ -23,7 +22,7 @@ export default function ContextMenu({
|
|||
user,
|
||||
ownId,
|
||||
}: {
|
||||
user: User;
|
||||
user: Readonly<{ UserId: number }>;
|
||||
ownId: number;
|
||||
}) {
|
||||
const [muted, setMuted] = useState(false);
|
||||
|
|
|
|||
|
|
@ -14,10 +14,12 @@ import {
|
|||
useSidebar,
|
||||
} from "@methanium/ui";
|
||||
import { ScreenShareOff } from "lucide-react";
|
||||
import { useUser, type User } from "@tensamin/user/context";
|
||||
import { useUserFields } from "@tensamin/user/context";
|
||||
import { useIsSpeaking, useLastSpeakingParticipantId } from "../speakingState";
|
||||
import { getAverageImageColor } from "./modals/base";
|
||||
|
||||
const USER_FIELDS = ["Avatar", "Display"] as const;
|
||||
|
||||
function getTrackPublicationBySource(
|
||||
participant: Participant | undefined,
|
||||
source: Track.Source,
|
||||
|
|
@ -62,10 +64,12 @@ function MobileCallPill({
|
|||
callId: string;
|
||||
}) {
|
||||
const { setOpenMobile } = useSidebar();
|
||||
const { get } = useUser();
|
||||
const lastSpeakingParticipantId = useLastSpeakingParticipantId();
|
||||
const isSpeaking = useIsSpeaking(lastSpeakingParticipantId ?? -1);
|
||||
const [lastSpeakingUser, setLastSpeakingUser] = useState<User | null>(null);
|
||||
const { data: lastSpeakingUser } = useUserFields(
|
||||
lastSpeakingParticipantId,
|
||||
USER_FIELDS,
|
||||
);
|
||||
const [avatarBackgroundColor, setAvatarBackgroundColor] = useState<
|
||||
string | undefined
|
||||
>(undefined);
|
||||
|
|
@ -83,25 +87,6 @@ function MobileCallPill({
|
|||
const [coords, setCoords] = useState(initialCoords);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (lastSpeakingParticipantId == null) {
|
||||
setLastSpeakingUser(null);
|
||||
return;
|
||||
}
|
||||
|
||||
let mounted = true;
|
||||
|
||||
void get(lastSpeakingParticipantId).then((user) => {
|
||||
if (mounted) {
|
||||
setLastSpeakingUser(user);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, [get, lastSpeakingParticipantId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!lastSpeakingUser?.Avatar) {
|
||||
setAvatarBackgroundColor(undefined);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { useUser, type User } from "@tensamin/user/context";
|
||||
import { useUserFields } from "@tensamin/user/context";
|
||||
import { useCall, getRoom } from "../store";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
|
|
@ -11,8 +11,43 @@ import {
|
|||
TooltipTrigger,
|
||||
} from "@methanium/ui";
|
||||
|
||||
const USER_FIELDS = ["Avatar", "Display"] as const;
|
||||
|
||||
function ParticipantAvatar({
|
||||
userId,
|
||||
portalContainer,
|
||||
}: {
|
||||
userId: number;
|
||||
portalContainer?: HTMLElement;
|
||||
}) {
|
||||
const { data: user } = useUserFields(userId, USER_FIELDS);
|
||||
if (!user) return null;
|
||||
|
||||
return (
|
||||
<div className="-ml-4">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Avatar className="size-7">
|
||||
<AvatarImage src={user.Avatar} />
|
||||
<AvatarFallback className="text-xs">
|
||||
{user.Display.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
}
|
||||
/>
|
||||
<TooltipContent
|
||||
side="bottom"
|
||||
portalProps={{ container: portalContainer }}
|
||||
>
|
||||
{user.Display}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function TopBar() {
|
||||
const { get } = useUser();
|
||||
const { load } = useStorage();
|
||||
const room = getRoom();
|
||||
const screenRef = useCall((state) => state.screenRef);
|
||||
|
|
@ -31,65 +66,23 @@ export default function TopBar() {
|
|||
: null;
|
||||
},
|
||||
).filter((participantId): participantId is number => participantId != null);
|
||||
const userIdsKey = userIds.join(",");
|
||||
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [ownId, setOwnId] = useState<number>();
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
const ids = userIdsKey === "" ? [] : userIdsKey.split(",").map(Number);
|
||||
void load("user_id").then(setOwnId);
|
||||
}, [load]);
|
||||
|
||||
void Promise.all(ids.map((id) => get(id)))
|
||||
.then(async (users) => {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ownId = await load("user_id");
|
||||
const ownUser = await get(ownId);
|
||||
|
||||
setUsers([ownUser, ...users]);
|
||||
})
|
||||
.catch(async () => {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ownId = await load("user_id");
|
||||
const ownUser = await get(ownId);
|
||||
|
||||
setUsers([ownUser]);
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [get, userIdsKey, load]);
|
||||
const participantIds = ownId === undefined ? userIds : [ownId, ...userIds];
|
||||
|
||||
return (
|
||||
<div className="w-full flex justify-between h-12">
|
||||
<div className="flex gap-1 m-3 ml-7">
|
||||
{users.map((user) => (
|
||||
<div key={user.UserId} className="-ml-4">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Avatar className="size-7">
|
||||
<AvatarImage src={user.Avatar} />
|
||||
<AvatarFallback className="text-xs">
|
||||
{user.Display.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
}
|
||||
/>
|
||||
<TooltipContent
|
||||
side="bottom"
|
||||
portalProps={{ container: portalContainer }}
|
||||
>
|
||||
{user.Display}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
{participantIds.map((userId) => (
|
||||
<ParticipantAvatar
|
||||
key={userId}
|
||||
userId={userId}
|
||||
portalContainer={portalContainer}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -70,7 +70,6 @@ type SendFn = (
|
|||
data: Record<string, unknown>,
|
||||
) => Promise<{ data: unknown }>;
|
||||
type LoadFn = (key: string) => Promise<unknown>;
|
||||
type GetUserFn = (userId: number) => Promise<{ PublicKey: string }>;
|
||||
type RemoteVideoTrackSelector = Track.Kind | Track.Source;
|
||||
|
||||
type Runtime = {
|
||||
|
|
@ -80,7 +79,7 @@ type Runtime = {
|
|||
}) => Promise<void>;
|
||||
send: SendFn;
|
||||
load: LoadFn;
|
||||
getUser: GetUserFn;
|
||||
getPublicKey: (userId: number) => Promise<string>;
|
||||
};
|
||||
|
||||
let _keyProvider: ExternalE2EEKeyProvider | null = null;
|
||||
|
|
@ -671,9 +670,7 @@ export async function sendCallInvite(userId: number) {
|
|||
throw new Error("Cannot send call invite without an active call.");
|
||||
}
|
||||
|
||||
const remotePublicKey = await runtime
|
||||
.getUser(userId)
|
||||
.then((data) => data.PublicKey);
|
||||
const remotePublicKey = await runtime.getPublicKey(userId);
|
||||
const secretId = deriveCallSecretId(callId);
|
||||
const wrapped = await wrapCallSecret({
|
||||
callSecret,
|
||||
|
|
@ -1255,7 +1252,8 @@ export function useInitializeCall() {
|
|||
navigate,
|
||||
send: send as SendFn,
|
||||
load: load as LoadFn,
|
||||
getUser: get as GetUserFn,
|
||||
getPublicKey: (userId) =>
|
||||
get(userId, ["PublicKey"]).then((user) => user.PublicKey),
|
||||
});
|
||||
}, [get, load, navigate, send]);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,54 +1,23 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { useCall } from "../store";
|
||||
import { useUser, type User } from "@tensamin/user/context";
|
||||
import { useUserFields } from "@tensamin/user/context";
|
||||
|
||||
const USER_FIELDS = ["Display"] as const;
|
||||
|
||||
function Participant({ userId }: { userId: number }) {
|
||||
const { data: user } = useUserFields(userId, USER_FIELDS);
|
||||
return user ? <p className="text-2xl">User: {user.Display}</p> : null;
|
||||
}
|
||||
|
||||
export default function Preview() {
|
||||
const { get } = useUser();
|
||||
const currentCallData = useCall((state) => state.currentCallData);
|
||||
|
||||
const [data, setData] = useState<User[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
if (!currentCallData?.exists) {
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}
|
||||
|
||||
void Promise.all(currentCallData.UserIds.map((id) => get(id)))
|
||||
.then((users) => {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
|
||||
setData(users);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
|
||||
setData([]);
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [currentCallData, get]);
|
||||
|
||||
return (
|
||||
<div className="w-full h-full flex items-center justify-center">
|
||||
{currentCallData?.exists ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
{data.map((user) => {
|
||||
return (
|
||||
<p key={user.UserId} className="text-2xl">
|
||||
User: {user.Display}
|
||||
</p>
|
||||
);
|
||||
})}
|
||||
{currentCallData.UserIds.map((userId) => (
|
||||
<Participant key={userId} userId={userId} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-2xl">Call expired</p>
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ import {
|
|||
} from "lucide-react";
|
||||
import { useState, useMemo, useEffect, useRef, type WheelEvent } from "react";
|
||||
import MediaSaveButton from "./mediaSaveButton";
|
||||
import { type User, useUser } from "@tensamin/user/context";
|
||||
import { useUserFields } from "@tensamin/user/context";
|
||||
|
||||
const zoomLevels = [1, 1.5, 2, 3];
|
||||
|
||||
|
|
@ -46,12 +46,7 @@ export default function Media({
|
|||
const wheelDelta = useRef(0);
|
||||
const hostname = useMemo(() => new URL(link).hostname, [link]);
|
||||
|
||||
// Get user's
|
||||
const { get } = useUser();
|
||||
const [user, setUser] = useState<undefined | User>(undefined);
|
||||
useEffect(() => {
|
||||
get(senderId).then(setUser);
|
||||
}, [senderId, get]);
|
||||
const { data: user } = useUserFields(senderId, ["Avatar", "Display"]);
|
||||
const avatar = user?.Avatar
|
||||
? `data:image/webp;base64,${user.Avatar}`
|
||||
: undefined;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import type { RawMessage } from "../values";
|
||||
import { AlertTriangle, Check, CheckLine, RefreshCw } from "lucide-react";
|
||||
import { memo, useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { User } from "@tensamin/user/context";
|
||||
import { type SelectedUser, useUserFields } from "@tensamin/user/context";
|
||||
|
||||
import {
|
||||
Avatar,
|
||||
|
|
@ -21,7 +21,6 @@ import { decryptChatText, encryptChatText } from "@tensamin/crypto/chatSecret";
|
|||
import { log, toast } from "@tensamin/shared/log";
|
||||
import { Emoji, Input, normalizeShortcode, Text } from "@methanium/ui/markdown";
|
||||
import { useRecordEmojiUse } from "./emojiRanks";
|
||||
import { useUser } from "@tensamin/user/context";
|
||||
import ReplyBox from "./replyBox";
|
||||
import { useHotkey } from "@tensamin/hotkeys";
|
||||
import { cancelMessageEditHotkey } from "../hotkeys";
|
||||
|
|
@ -40,7 +39,7 @@ function MessageComponent({
|
|||
decryptionFailed?: boolean;
|
||||
};
|
||||
onSetEditing: (editing: boolean) => void;
|
||||
user: User | null;
|
||||
user: SelectedUser<readonly ["UserId", "Avatar", "Display"]> | null;
|
||||
}) {
|
||||
const actuallyFailed =
|
||||
(message.failed && message.MessageState === "awaiting") ||
|
||||
|
|
@ -150,13 +149,14 @@ function MessageComponent({
|
|||
removeReaction,
|
||||
replyTo,
|
||||
} = useChat();
|
||||
const { get: getUser } = useUser();
|
||||
const [replyMessage, setReplyMessage] = useState<RawMessage | null>(null);
|
||||
const [replyUser, setReplyUser] = useState<User | null>(null);
|
||||
const { data: replyUser } = useUserFields(replyMessage?.SenderId ?? null, [
|
||||
"Avatar",
|
||||
"Display",
|
||||
]);
|
||||
useEffect(() => {
|
||||
if (!message.ReplyId || !ownId || !chatSecret) {
|
||||
setReplyMessage(null);
|
||||
setReplyUser(null);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -168,25 +168,20 @@ function MessageComponent({
|
|||
send,
|
||||
})
|
||||
.then(async (reply) => {
|
||||
const [Content, author] = await Promise.all([
|
||||
decryptChatText(chatSecret, reply.Content),
|
||||
getUser(reply.SenderId),
|
||||
]);
|
||||
const Content = await decryptChatText(chatSecret, reply.Content);
|
||||
if (!active) return;
|
||||
setReplyMessage({ ...reply, Content });
|
||||
setReplyUser(author);
|
||||
})
|
||||
.catch((err) => {
|
||||
if (!active) return;
|
||||
setReplyMessage(null);
|
||||
setReplyUser(null);
|
||||
log(1, "chat", "red", "Failed to get replied-to message", err);
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [chatSecret, getUser, message.ReplyId, ownId, send, userId]);
|
||||
}, [chatSecret, message.ReplyId, ownId, send, userId]);
|
||||
const recordUse = useRecordEmojiUse();
|
||||
const editingRef = useRef(editing);
|
||||
const onSetEditingRef = useRef(onSetEditing);
|
||||
|
|
|
|||
|
|
@ -7,11 +7,13 @@ import {
|
|||
Skeleton,
|
||||
} from "@methanium/ui";
|
||||
import { Text } from "@methanium/ui/markdown";
|
||||
import type { User } from "@tensamin/user/context";
|
||||
import type { SelectedUser } from "@tensamin/user/context";
|
||||
import Wrapper from "@tensamin/user/wrapper";
|
||||
import { Forward, X } from "lucide-react";
|
||||
|
||||
function ReplyUser({ user }: { user: User }) {
|
||||
type ReplyUserData = SelectedUser<readonly ["Avatar", "Display"]>;
|
||||
|
||||
function ReplyUser({ user }: { user: ReplyUserData }) {
|
||||
return (
|
||||
<div className="flex gap-1 items-center">
|
||||
<Avatar className="h-5 w-5 shrink-0">
|
||||
|
|
@ -40,7 +42,7 @@ export default function ReplyBox({
|
|||
content?: string;
|
||||
loading?: boolean;
|
||||
onDismiss?: () => void;
|
||||
user?: User;
|
||||
user?: ReplyUserData;
|
||||
userId?: number;
|
||||
variant: "composer" | "message";
|
||||
}) {
|
||||
|
|
@ -71,6 +73,7 @@ export default function ReplyBox({
|
|||
) : userId ? (
|
||||
<Wrapper
|
||||
userId={userId}
|
||||
fields={["Avatar", "Display"]}
|
||||
loading={<Skeleton className="h-5 w-5 rounded-full" />}
|
||||
component={(resolvedUser) => <ReplyUser user={resolvedUser} />}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -458,7 +458,7 @@ export default function Provider({ children }: { children: ReactNode }) {
|
|||
secretId,
|
||||
version: CHAT_SECRET_VERSION,
|
||||
});
|
||||
const peerUser = await getUser(userIdValue);
|
||||
const peerUser = await getUser(userIdValue, ["PublicKey"]);
|
||||
const peerWrapped = await wrapChatSecret({
|
||||
chatSecret: rawSecret,
|
||||
recipientKemPublicKey: kemPublicKeyFromPublicKeyBundle(
|
||||
|
|
|
|||
|
|
@ -598,6 +598,7 @@ export default function Screen() {
|
|||
<Wrapper
|
||||
key={getMessageRenderKey(message)}
|
||||
userId={message.SenderId}
|
||||
fields={["UserId", "Avatar", "Display"]}
|
||||
loading={null}
|
||||
component={(user) => (
|
||||
<>
|
||||
|
|
|
|||
|
|
@ -7,3 +7,4 @@
|
|||
- Drop any unique reactions above 10
|
||||
- Reply jumping
|
||||
- Add emoji picker
|
||||
- Improve arrow-up hotkey
|
||||
|
|
|
|||
|
|
@ -99,7 +99,11 @@ export default function Provider(props: { children: React.ReactNode }) {
|
|||
}
|
||||
}
|
||||
|
||||
const user = await get(data.SenderId);
|
||||
const user = await get(data.SenderId, [
|
||||
"UserId",
|
||||
"Display",
|
||||
"Avatar",
|
||||
]);
|
||||
|
||||
if (isTauri()) {
|
||||
if (!appFocused) return;
|
||||
|
|
|
|||
|
|
@ -1,3 +1 @@
|
|||
- Tauri notifications
|
||||
- Mobile notifications channel setup
|
||||
- Add notification symbol / outline to user modal
|
||||
|
|
|
|||
|
|
@ -11,10 +11,25 @@ import {
|
|||
Input,
|
||||
useIsMobile,
|
||||
} from "@methanium/ui";
|
||||
import { useUser, type User } from "@tensamin/user/context";
|
||||
import {
|
||||
useUser,
|
||||
useUserFields,
|
||||
type SelectedUser,
|
||||
} from "@tensamin/user/context";
|
||||
import { Check } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
const PROFILE_FIELDS = [
|
||||
"Avatar",
|
||||
"Display",
|
||||
"Username",
|
||||
"About",
|
||||
"UserId",
|
||||
] as const;
|
||||
type ProfileDraft = Partial<
|
||||
Omit<SelectedUser<typeof PROFILE_FIELDS>, "UserId">
|
||||
>;
|
||||
|
||||
async function prepImage(
|
||||
file: File,
|
||||
size = 300,
|
||||
|
|
@ -44,12 +59,13 @@ async function prepImage(
|
|||
}
|
||||
|
||||
export default function Page() {
|
||||
const { get, update } = useUser();
|
||||
const { updateProfile } = useUser();
|
||||
const { load } = useStorage();
|
||||
const { send } = useMTP();
|
||||
const isMobile = useIsMobile();
|
||||
const [currentUser, setCurrentUser] = useState<User | null>(null);
|
||||
const [draftUser, setDraftUser] = useState<Partial<User>>({});
|
||||
const [userId, setUserId] = useState<number | null>(null);
|
||||
const { data: currentUser } = useUserFields(userId, PROFILE_FIELDS);
|
||||
const [draftUser, setDraftUser] = useState<ProfileDraft>({});
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [saveSucceeded, setSaveSucceeded] = useState(false);
|
||||
const avatarUploadRef = useRef<HTMLInputElement>(null);
|
||||
|
|
@ -57,18 +73,23 @@ export default function Page() {
|
|||
const effectiveAvatar =
|
||||
draftUser.Avatar === "none" ? undefined : draftUser.Avatar;
|
||||
const updateDraftUser = (
|
||||
updater: (previous: Partial<User>) => Partial<User>,
|
||||
updater: (previous: ProfileDraft) => ProfileDraft,
|
||||
) => {
|
||||
setSaveSucceeded(false);
|
||||
setErrorMessage("");
|
||||
setDraftUser(updater);
|
||||
};
|
||||
useEffect(() => {
|
||||
void (async () => setCurrentUser(await get(await load("user_id"))))();
|
||||
}, [get, load]);
|
||||
void load("user_id").then(setUserId);
|
||||
}, [load]);
|
||||
useEffect(() => {
|
||||
if (!currentUser || draftInitializedRef.current) return;
|
||||
setDraftUser(currentUser);
|
||||
setDraftUser({
|
||||
Avatar: currentUser.Avatar,
|
||||
Display: currentUser.Display,
|
||||
Username: currentUser.Username,
|
||||
About: currentUser.About,
|
||||
});
|
||||
draftInitializedRef.current = true;
|
||||
}, [currentUser]);
|
||||
async function handleAvatarUpload(file: File) {
|
||||
|
|
@ -127,7 +148,7 @@ export default function Page() {
|
|||
onChange={(event) =>
|
||||
updateDraftUser((previous) => ({
|
||||
...previous,
|
||||
display: event.target.value,
|
||||
Display: event.target.value,
|
||||
}))
|
||||
}
|
||||
placeholder="Display Name"
|
||||
|
|
@ -138,7 +159,7 @@ export default function Page() {
|
|||
onChange={(event) =>
|
||||
updateDraftUser((previous) => ({
|
||||
...previous,
|
||||
username: event.target.value,
|
||||
Username: event.target.value,
|
||||
}))
|
||||
}
|
||||
placeholder="Username"
|
||||
|
|
@ -150,7 +171,7 @@ export default function Page() {
|
|||
fontSize=".875rem"
|
||||
placeholder="About Me"
|
||||
setValue={(value) =>
|
||||
updateDraftUser((previous) => ({ ...previous, about: value }))
|
||||
updateDraftUser((previous) => ({ ...previous, About: value }))
|
||||
}
|
||||
value={draftUser.About || ""}
|
||||
/>
|
||||
|
|
@ -180,13 +201,7 @@ export default function Page() {
|
|||
if (response.type.startsWith("Error")) {
|
||||
throw new Error(response.type);
|
||||
}
|
||||
const updatedUser = mtp.GetUserData.response.parse({
|
||||
...currentUser,
|
||||
...draftUser,
|
||||
});
|
||||
await update(updatedUser);
|
||||
setCurrentUser(updatedUser);
|
||||
setDraftUser(updatedUser);
|
||||
await updateProfile(currentUser.UserId, validation.data);
|
||||
setSaveSucceeded(true);
|
||||
setErrorMessage("");
|
||||
} catch (error) {
|
||||
|
|
|
|||
|
|
@ -260,20 +260,13 @@ export const mtp = {
|
|||
UserState: clientUserStateSchema,
|
||||
}),
|
||||
},
|
||||
SetUserState: {
|
||||
request: z.object({
|
||||
UserState: userPresencePreferenceSchema,
|
||||
}),
|
||||
response: z.object({
|
||||
UserState: userPresencePreferenceSchema,
|
||||
}),
|
||||
},
|
||||
ChangeUserData: {
|
||||
request: z
|
||||
.object({
|
||||
About: userFields.About,
|
||||
Avatar: userFields.Avatar,
|
||||
Display: userFields.Display,
|
||||
OnlineStatus: userPresencePreferenceSchema,
|
||||
PublicKey: userFields.PublicKey,
|
||||
Status: userFields.Status,
|
||||
Username: userFields.Username,
|
||||
|
|
|
|||
|
|
@ -1,2 +1 @@
|
|||
- Add `notifications: number` to contacts
|
||||
- Store private key in a device bound session
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"scripts": {
|
||||
"format": "pnpm exec prettier --write .",
|
||||
"lint": "eslint src",
|
||||
"test": "vitest run",
|
||||
"build": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
|
|
|
|||
|
|
@ -4,8 +4,10 @@ import {
|
|||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
} from "react";
|
||||
import { useMTP, type ProtocolMessage } from "@tensamin/mtp";
|
||||
|
||||
|
|
@ -19,9 +21,21 @@ import type z from "zod";
|
|||
import { createCache } from "@tensamin/cache";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import { useSession } from "@tensamin/storage/session";
|
||||
import { getChangedUserFields, selectUserFields } from "./selection";
|
||||
|
||||
export { getChangedUserFields, selectUserFields } from "./selection";
|
||||
|
||||
export type User = z.infer<typeof schemas.GetUserData.response>;
|
||||
type ClientUserState = z.infer<typeof clientUserStateSchema>;
|
||||
export type UserField = keyof User;
|
||||
export type UserFields = readonly [UserField, ...UserField[]];
|
||||
export type SelectedUser<Fields extends readonly UserField[]> = Readonly<
|
||||
Pick<User, Fields[number]>
|
||||
>;
|
||||
export type UserProfilePatch = Omit<
|
||||
z.infer<typeof schemas.ChangeUserData.request>,
|
||||
"OnlineStatus"
|
||||
>;
|
||||
|
||||
export function mergeTransientPresence<T extends { UserId: number }>(
|
||||
user: T,
|
||||
|
|
@ -34,8 +48,22 @@ export function mergeTransientPresence<T extends { UserId: number }>(
|
|||
const USER_CACHE_MAX_AGE = 5 * 60 * 1000;
|
||||
|
||||
interface contextValue {
|
||||
get(userId: number): Promise<User>;
|
||||
update(user: User): Promise<void>;
|
||||
get<const Fields extends UserFields>(
|
||||
userId: number,
|
||||
fields: Fields,
|
||||
): Promise<SelectedUser<Fields>>;
|
||||
peek<const Fields extends UserFields>(
|
||||
userId: number,
|
||||
fields: Fields,
|
||||
): SelectedUser<Fields> | undefined;
|
||||
subscribe(
|
||||
userId: number,
|
||||
fields: readonly UserField[],
|
||||
listener: () => void,
|
||||
): () => void;
|
||||
getVersion(userId: number, fields: readonly UserField[]): string;
|
||||
updateProfile(userId: number, patch: UserProfilePatch): Promise<void>;
|
||||
updateState(userId: number, state: ClientUserState): void;
|
||||
}
|
||||
|
||||
const UserContext = createContext<contextValue | undefined>(undefined);
|
||||
|
|
@ -48,16 +76,24 @@ const UserContext = createContext<contextValue | undefined>(undefined);
|
|||
export default function UserProvider(props: { children: ReactNode }) {
|
||||
const storageRef = useRef<Record<number, User>>({});
|
||||
const pendingRef = useRef<Record<number, Promise<User> | undefined>>({});
|
||||
const profileUpdateQueuesRef = useRef(new Map<number, Promise<void>>());
|
||||
const profileGenerationsRef = useRef(new Map<number, number>());
|
||||
const checkedAtRef = useRef<Record<number, number>>({});
|
||||
const presenceRef = useRef(new Map<number, ClientUserState>());
|
||||
const durableProfileRef = useRef<Record<number, User>>({});
|
||||
const listenersRef = useRef(
|
||||
new Map<
|
||||
number,
|
||||
Set<{ fields: ReadonlySet<UserField>; listener: () => void }>
|
||||
>(),
|
||||
);
|
||||
const revisionsRef = useRef(new Map<number, Map<UserField, number>>());
|
||||
|
||||
const { send, subscribePush } = useMTP();
|
||||
const { load } = useStorage();
|
||||
const { contacts } = useSession();
|
||||
const [accountId, setAccountId] = useState<number | null>(null);
|
||||
const [cacheVersion, setCacheVersion] = useState(0);
|
||||
const [sessionId, setSessionId] = useState<number | null>(null);
|
||||
const accountIdRef = useRef<number | null>(null);
|
||||
const contactsRef = useRef(contacts);
|
||||
const initialStatesRef = useRef(
|
||||
new Map<number, z.infer<typeof publicUserStateSchema>>(),
|
||||
|
|
@ -71,40 +107,78 @@ export default function UserProvider(props: { children: ReactNode }) {
|
|||
return mergeTransientPresence(user, presenceRef.current);
|
||||
}, []);
|
||||
|
||||
const publishUser = useCallback((userId: number, user?: User) => {
|
||||
const previous = storageRef.current[userId];
|
||||
if (user) storageRef.current[userId] = user;
|
||||
else delete storageRef.current[userId];
|
||||
|
||||
const changedFields = getChangedUserFields(previous, user);
|
||||
if (changedFields.length === 0) return;
|
||||
|
||||
let revisions = revisionsRef.current.get(userId);
|
||||
if (!revisions) {
|
||||
revisions = new Map();
|
||||
revisionsRef.current.set(userId, revisions);
|
||||
}
|
||||
for (const field of changedFields) {
|
||||
revisions.set(field, (revisions.get(field) ?? 0) + 1);
|
||||
}
|
||||
|
||||
const changed = new Set<UserField>(changedFields);
|
||||
for (const entry of listenersRef.current.get(userId) ?? []) {
|
||||
if ([...entry.fields].some((field) => changed.has(field))) {
|
||||
entry.listener();
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const installProfile = useCallback(
|
||||
(profile: User) => {
|
||||
durableProfileRef.current[profile.UserId] = profile;
|
||||
publishUser(profile.UserId, mergeUserPresence(profile));
|
||||
},
|
||||
[mergeUserPresence, publishUser],
|
||||
);
|
||||
|
||||
const applyUserState = useCallback(
|
||||
(userId: number, state: ClientUserState, privateState = false) => {
|
||||
const currentAccountId = accountIdRef.current;
|
||||
const known =
|
||||
userId === accountId ||
|
||||
userId === currentAccountId ||
|
||||
durableProfileRef.current[userId] !== undefined ||
|
||||
contactsRef.current.some((contact) => contact.UserId === userId);
|
||||
if (!known) return false;
|
||||
|
||||
if (state === "user_invisible" && userId !== accountId) return false;
|
||||
if (userId === accountId && !privateState) return false;
|
||||
if (state === "user_invisible" && userId !== currentAccountId)
|
||||
return false;
|
||||
if (userId === currentAccountId && !privateState) return false;
|
||||
if (presenceRef.current.get(userId) === state) return true;
|
||||
|
||||
presenceRef.current.set(userId, state);
|
||||
const current = storageRef.current[userId];
|
||||
if (current) storageRef.current[userId] = mergeUserPresence(current);
|
||||
setCacheVersion((version) => version + 1);
|
||||
const profile = durableProfileRef.current[userId];
|
||||
if (profile) publishUser(userId, mergeUserPresence(profile));
|
||||
return true;
|
||||
},
|
||||
[accountId, mergeUserPresence],
|
||||
[mergeUserPresence, publishUser],
|
||||
);
|
||||
|
||||
const removePresence = useCallback((userId: number) => {
|
||||
presenceRef.current.delete(userId);
|
||||
initialStatesRef.current.delete(userId);
|
||||
delete checkedAtRef.current[userId];
|
||||
setCacheVersion((version) => version + 1);
|
||||
}, []);
|
||||
const removePresence = useCallback(
|
||||
(userId: number) => {
|
||||
const removed = presenceRef.current.delete(userId);
|
||||
initialStatesRef.current.delete(userId);
|
||||
delete checkedAtRef.current[userId];
|
||||
if (!removed) return;
|
||||
const profile = durableProfileRef.current[userId];
|
||||
if (profile) publishUser(userId, profile);
|
||||
},
|
||||
[publishUser],
|
||||
);
|
||||
|
||||
const handleStatePush = useCallback(
|
||||
async (message: ProtocolMessage) => {
|
||||
if (!accountId || !sessionId) return;
|
||||
if (!accountId) return;
|
||||
const data = message.data as Record<string, unknown>;
|
||||
if (message.type === "GetStates") {
|
||||
if (Number(data.SessionId) !== sessionId) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(data.MissingUserIds)) {
|
||||
for (const userId of data.MissingUserIds) {
|
||||
if (typeof userId === "number") removePresence(userId);
|
||||
|
|
@ -126,36 +200,34 @@ export default function UserProvider(props: { children: ReactNode }) {
|
|||
return;
|
||||
}
|
||||
if (message.type !== "ClientChanged") return;
|
||||
if (Number(data.SessionId) !== sessionId) return;
|
||||
const parsed = schemas.ClientChanged.response.safeParse(data);
|
||||
if (!parsed.success) return;
|
||||
applyUserState(parsed.data.UserId, parsed.data.UserState, true);
|
||||
},
|
||||
[accountId, applyUserState, removePresence, sessionId],
|
||||
[accountId, applyUserState, removePresence],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void load("user_id").then((accountId) => {
|
||||
accountIdRef.current = accountId;
|
||||
setAccountId(accountId);
|
||||
});
|
||||
void load("session_id").then((value) => {
|
||||
setSessionId(value);
|
||||
});
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!accountId || !sessionId) return;
|
||||
return subscribePush(handleStatePush);
|
||||
}, [accountId, handleStatePush, sessionId, subscribePush]);
|
||||
const getAccountId = useCallback(async () => {
|
||||
if (accountIdRef.current !== null) return accountIdRef.current;
|
||||
const value = await load("user_id");
|
||||
accountIdRef.current = value;
|
||||
return value;
|
||||
}, [load]);
|
||||
|
||||
/**
|
||||
* Executes get.
|
||||
* @param userId Parameter userId.
|
||||
* @returns Promise<User>.
|
||||
*/
|
||||
const get = useCallback(
|
||||
useEffect(() => {
|
||||
if (!accountId) return;
|
||||
return subscribePush(handleStatePush);
|
||||
}, [accountId, handleStatePush, subscribePush]);
|
||||
|
||||
const loadUser = useCallback(
|
||||
async (userId: number): Promise<User> => {
|
||||
void cacheVersion;
|
||||
if (userId == null) {
|
||||
throw new Error("userId is required");
|
||||
}
|
||||
|
|
@ -166,39 +238,45 @@ export default function UserProvider(props: { children: ReactNode }) {
|
|||
}
|
||||
|
||||
const request = (async () => {
|
||||
const cache = createCache(String(accountId ?? userId));
|
||||
const cache = createCache(String(await getAccountId()));
|
||||
const cachedValue =
|
||||
storageRef.current[userId] ?? (await cache.profiles.get(userId));
|
||||
durableProfileRef.current[userId] ??
|
||||
(await cache.profiles.get(userId));
|
||||
const cachedResult =
|
||||
schemas.GetUserData.response.safeParse(cachedValue);
|
||||
const cached = cachedResult.success ? cachedResult.data : undefined;
|
||||
if (cached) {
|
||||
durableProfileRef.current[userId] = cached;
|
||||
const merged = mergeUserPresence(cached);
|
||||
storageRef.current[userId] = merged;
|
||||
installProfile(cached);
|
||||
const checkedAt = checkedAtRef.current[userId];
|
||||
if (!checkedAt || Date.now() - checkedAt < USER_CACHE_MAX_AGE) {
|
||||
checkedAtRef.current[userId] = Date.now();
|
||||
return merged;
|
||||
return storageRef.current[userId];
|
||||
}
|
||||
}
|
||||
try {
|
||||
const profileGeneration =
|
||||
profileGenerationsRef.current.get(userId) ?? 0;
|
||||
const userData = await send("GetUserData", { UserId: userId });
|
||||
if (userData.type === "ErrorNotFound" || userData.data.UserId === 0) {
|
||||
delete storageRef.current[userId];
|
||||
delete durableProfileRef.current[userId];
|
||||
delete checkedAtRef.current[userId];
|
||||
publishUser(userId);
|
||||
await cache.profiles.delete(userId);
|
||||
throw new Error("GetUserData failed: user not found");
|
||||
}
|
||||
if (userData.type.startsWith("Error")) {
|
||||
throw new Error(`GetUserData failed: ${userData.type}`);
|
||||
}
|
||||
const user = mergeUserPresence(userData.data);
|
||||
durableProfileRef.current[userId] = userData.data;
|
||||
storageRef.current[userId] = user;
|
||||
if (
|
||||
profileGeneration !==
|
||||
(profileGenerationsRef.current.get(userId) ?? 0) &&
|
||||
storageRef.current[userId]
|
||||
) {
|
||||
return storageRef.current[userId];
|
||||
}
|
||||
installProfile(userData.data);
|
||||
checkedAtRef.current[userId] = Date.now();
|
||||
return user;
|
||||
return storageRef.current[userId];
|
||||
} catch (error) {
|
||||
if (cached && storageRef.current[userId]) {
|
||||
checkedAtRef.current[userId] = Date.now();
|
||||
|
|
@ -216,26 +294,91 @@ export default function UserProvider(props: { children: ReactNode }) {
|
|||
delete pendingRef.current[userId];
|
||||
}
|
||||
},
|
||||
[accountId, cacheVersion, mergeUserPresence, send],
|
||||
[getAccountId, installProfile, publishUser, send],
|
||||
);
|
||||
|
||||
const update = useCallback(
|
||||
async (user: User) => {
|
||||
const durableProfile = {
|
||||
...user,
|
||||
OnlineStatus:
|
||||
durableProfileRef.current[user.UserId]?.OnlineStatus ??
|
||||
user.OnlineStatus,
|
||||
} as User;
|
||||
await createCache(String(accountId ?? user.UserId)).profiles.put(
|
||||
durableProfile,
|
||||
);
|
||||
durableProfileRef.current[user.UserId] = durableProfile;
|
||||
storageRef.current[user.UserId] = mergeUserPresence(durableProfile);
|
||||
checkedAtRef.current[user.UserId] = Date.now();
|
||||
setCacheVersion((version) => version + 1);
|
||||
const get = useCallback(
|
||||
async <const Fields extends UserFields>(
|
||||
userId: number,
|
||||
fields: Fields,
|
||||
): Promise<SelectedUser<Fields>> => {
|
||||
return selectUserFields(await loadUser(userId), fields);
|
||||
},
|
||||
[accountId, mergeUserPresence],
|
||||
[loadUser],
|
||||
);
|
||||
|
||||
const peek = useCallback(
|
||||
<const Fields extends UserFields>(userId: number, fields: Fields) => {
|
||||
const user = storageRef.current[userId];
|
||||
return user ? selectUserFields(user, fields) : undefined;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const subscribe = useCallback(
|
||||
(userId: number, fields: readonly UserField[], listener: () => void) => {
|
||||
let listeners = listenersRef.current.get(userId);
|
||||
if (!listeners) {
|
||||
listeners = new Set();
|
||||
listenersRef.current.set(userId, listeners);
|
||||
}
|
||||
const entry = { fields: new Set(fields), listener };
|
||||
listeners.add(entry);
|
||||
return () => {
|
||||
listeners.delete(entry);
|
||||
if (listeners.size === 0) listenersRef.current.delete(userId);
|
||||
};
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const getVersion = useCallback(
|
||||
(userId: number, fields: readonly UserField[]) => {
|
||||
const revisions = revisionsRef.current.get(userId);
|
||||
return fields
|
||||
.map((field) => `${field}:${revisions?.get(field) ?? 0}`)
|
||||
.join("|");
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const updateProfile = useCallback(
|
||||
async (userId: number, patch: UserProfilePatch) => {
|
||||
const previousUpdate = profileUpdateQueuesRef.current.get(userId);
|
||||
const update = (
|
||||
previousUpdate?.catch(() => undefined) ?? Promise.resolve()
|
||||
).then(async () => {
|
||||
const current = durableProfileRef.current[userId];
|
||||
if (!current) throw new Error(`User ${userId} is not loaded`);
|
||||
profileGenerationsRef.current.set(
|
||||
userId,
|
||||
(profileGenerationsRef.current.get(userId) ?? 0) + 1,
|
||||
);
|
||||
const profile = schemas.GetUserData.response.parse({
|
||||
...current,
|
||||
...patch,
|
||||
});
|
||||
installProfile(profile);
|
||||
checkedAtRef.current[userId] = Date.now();
|
||||
await createCache(String(await getAccountId())).profiles.put(profile);
|
||||
});
|
||||
profileUpdateQueuesRef.current.set(userId, update);
|
||||
try {
|
||||
await update;
|
||||
} finally {
|
||||
if (profileUpdateQueuesRef.current.get(userId) === update) {
|
||||
profileUpdateQueuesRef.current.delete(userId);
|
||||
}
|
||||
}
|
||||
},
|
||||
[getAccountId, installProfile],
|
||||
);
|
||||
|
||||
const updateState = useCallback(
|
||||
(userId: number, state: ClientUserState) => {
|
||||
applyUserState(userId, state, true);
|
||||
},
|
||||
[applyUserState],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -247,7 +390,7 @@ export default function UserProvider(props: { children: ReactNode }) {
|
|||
].filter((userId, index, all) => all.indexOf(userId) === index);
|
||||
for (const userId of userIds) {
|
||||
try {
|
||||
await get(userId);
|
||||
await loadUser(userId);
|
||||
const state = initialStatesRef.current.get(userId);
|
||||
if (state && applyUserState(userId, state)) {
|
||||
initialStatesRef.current.delete(userId);
|
||||
|
|
@ -257,12 +400,22 @@ export default function UserProvider(props: { children: ReactNode }) {
|
|||
}
|
||||
}
|
||||
})();
|
||||
}, [accountId, applyUserState, contacts, get]);
|
||||
}, [accountId, applyUserState, contacts, loadUser]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
get,
|
||||
peek,
|
||||
subscribe,
|
||||
getVersion,
|
||||
updateProfile,
|
||||
updateState,
|
||||
}),
|
||||
[get, getVersion, peek, subscribe, updateProfile, updateState],
|
||||
);
|
||||
|
||||
return (
|
||||
<UserContext.Provider value={{ get, update }}>
|
||||
{props.children}
|
||||
</UserContext.Provider>
|
||||
<UserContext.Provider value={value}>{props.children}</UserContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -278,3 +431,63 @@ export function useUser(): contextValue {
|
|||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
export type UserLoadState<Fields extends readonly UserField[]> =
|
||||
| { data: undefined; error: undefined; loading: true }
|
||||
| { data: undefined; error: unknown; loading: false }
|
||||
| { data: SelectedUser<Fields>; error: undefined; loading: false };
|
||||
|
||||
export function useUserFields<const Fields extends UserFields>(
|
||||
userId: number | null,
|
||||
fields: Fields,
|
||||
): UserLoadState<Fields> {
|
||||
const { get, getVersion, peek, subscribe } = useUser();
|
||||
const fieldKey = fields.join("|");
|
||||
const selectedFields = useMemo(
|
||||
() => fieldKey.split("|") as unknown as Fields,
|
||||
[fieldKey],
|
||||
);
|
||||
const requestKey = `${userId ?? "unresolved"}:${fieldKey}`;
|
||||
const [failure, setFailure] = useState<{
|
||||
error: unknown;
|
||||
requestKey: string;
|
||||
}>();
|
||||
|
||||
const version = useSyncExternalStore(
|
||||
useCallback(
|
||||
(listener) =>
|
||||
userId === null
|
||||
? () => undefined
|
||||
: subscribe(userId, selectedFields, listener),
|
||||
[selectedFields, subscribe, userId],
|
||||
),
|
||||
useCallback(
|
||||
() =>
|
||||
userId === null ? "unresolved" : getVersion(userId, selectedFields),
|
||||
[getVersion, selectedFields, userId],
|
||||
),
|
||||
() => "server",
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (userId === null) return;
|
||||
let active = true;
|
||||
void get(userId, selectedFields).catch((nextError: unknown) => {
|
||||
if (active) setFailure({ error: nextError, requestKey });
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [get, requestKey, selectedFields, userId]);
|
||||
|
||||
const data = useMemo(() => {
|
||||
void version;
|
||||
return userId === null ? undefined : peek(userId, selectedFields);
|
||||
}, [peek, selectedFields, userId, version]);
|
||||
|
||||
if (data) return { data, error: undefined, loading: false };
|
||||
if (failure?.requestKey === requestKey) {
|
||||
return { data: undefined, error: failure.error, loading: false };
|
||||
}
|
||||
return { data: undefined, error: undefined, loading: true };
|
||||
}
|
||||
|
|
|
|||
28
packages/user/src/selection.test.ts
Normal file
28
packages/user/src/selection.test.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { User } from "./context";
|
||||
import { getChangedUserFields, selectUserFields } from "./selection";
|
||||
|
||||
const user = {
|
||||
Avatar: undefined,
|
||||
Display: "Alice",
|
||||
IotaId: 1,
|
||||
OmikronConnections: [],
|
||||
OnlineStatus: "user_online",
|
||||
PublicKey: "AA==",
|
||||
SubEnd: 0,
|
||||
SubLevel: 0,
|
||||
UserId: 1,
|
||||
Username: "alice",
|
||||
} satisfies User;
|
||||
|
||||
describe("presence selection", () => {
|
||||
it("notifies OnlineStatus selections when presence changes", () => {
|
||||
const next = { ...user, OnlineStatus: "user_dnd" as const };
|
||||
|
||||
expect(getChangedUserFields(user, next)).toEqual(["OnlineStatus"]);
|
||||
expect(selectUserFields(next, ["OnlineStatus"])).toEqual({
|
||||
OnlineStatus: "user_dnd",
|
||||
});
|
||||
});
|
||||
});
|
||||
40
packages/user/src/selection.ts
Normal file
40
packages/user/src/selection.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import type { User, UserField, UserFields, SelectedUser } from "./context";
|
||||
|
||||
const USER_FIELD_MAP = {
|
||||
About: true,
|
||||
Avatar: true,
|
||||
Display: true,
|
||||
IotaId: true,
|
||||
OmikronConnections: true,
|
||||
OmikronId: true,
|
||||
OnlineStatus: true,
|
||||
PublicKey: true,
|
||||
Status: true,
|
||||
SubEnd: true,
|
||||
SubLevel: true,
|
||||
UserId: true,
|
||||
Username: true,
|
||||
} satisfies Record<UserField, true>;
|
||||
|
||||
const USER_FIELDS = Object.keys(USER_FIELD_MAP) as UserField[];
|
||||
|
||||
export function selectUserFields<const Fields extends UserFields>(
|
||||
user: User,
|
||||
fields: Fields,
|
||||
): SelectedUser<Fields> {
|
||||
return Object.fromEntries(
|
||||
fields.map((field) => [field, user[field]]),
|
||||
) as SelectedUser<Fields>;
|
||||
}
|
||||
|
||||
export function getChangedUserFields(
|
||||
previous: User | undefined,
|
||||
next: User | undefined,
|
||||
): UserField[] {
|
||||
if ((previous === undefined) !== (next === undefined)) {
|
||||
return [...USER_FIELDS];
|
||||
}
|
||||
return USER_FIELDS.filter(
|
||||
(field) => !Object.is(previous?.[field], next?.[field]),
|
||||
);
|
||||
}
|
||||
|
|
@ -1,48 +1,47 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { useUser, type User } from "./context";
|
||||
import { type SelectedUser, type UserFields, useUserFields } from "./context";
|
||||
|
||||
import { failedUser } from "@tensamin/shared/data";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
|
||||
// Wrapper function to pass user data to some component
|
||||
export default function Wrapper(props: {
|
||||
export default function Wrapper<const Fields extends UserFields>(props: {
|
||||
userId: number | "own";
|
||||
fields: Fields;
|
||||
loading: React.ReactNode;
|
||||
component: (user: User) => React.ReactNode;
|
||||
component: (user: SelectedUser<Fields>) => React.ReactNode;
|
||||
}) {
|
||||
const { get } = useUser();
|
||||
const { load } = useStorage();
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [ownUserId, setOwnUserId] = useState<number | null>(null);
|
||||
const [ownUserError, setOwnUserError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (props.userId == null) return;
|
||||
|
||||
if (props.userId !== "own") return;
|
||||
let active = true;
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const userId =
|
||||
props.userId === "own" ? await load("user_id") : props.userId;
|
||||
const value = await get(userId);
|
||||
|
||||
void load("user_id").then(
|
||||
(value) => {
|
||||
if (active) {
|
||||
setUser(value);
|
||||
setOwnUserId(value);
|
||||
setOwnUserError(false);
|
||||
}
|
||||
} catch {
|
||||
if (active) {
|
||||
setUser(failedUser);
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
},
|
||||
() => {
|
||||
if (active) setOwnUserError(true);
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [load, get, props.userId]);
|
||||
}, [load, props.userId]);
|
||||
|
||||
if (props.userId == null) {
|
||||
return <>{props.component(failedUser)}</>;
|
||||
const userId = props.userId === "own" ? ownUserId : props.userId;
|
||||
const result = useUserFields(userId, props.fields);
|
||||
if (
|
||||
(props.userId === "own" && ownUserError) ||
|
||||
(!result.loading && !result.data)
|
||||
) {
|
||||
return <>{props.component(failedUser as SelectedUser<Fields>)}</>;
|
||||
}
|
||||
|
||||
return <>{user ? props.component(user) : props.loading}</>;
|
||||
return <>{result.data ? props.component(result.data) : props.loading}</>;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue