frontend client for gemstone. decentralised workplace app

Compare changes

Choose any two refs to compare.

Changed files
+202 -52
assets
src
components
Auth
Chat
Invites
lib
providers
+67 -1
src/lib/utils/atproto/index.ts
···
atUriAuthoritySchema,
nsidSchema,
} from "@/lib/types/atproto";
-
import { comAtprotoRepoGetRecordResponseSchema } from "@/lib/types/lexicon/com.atproto.repo.getRecord";
import type { Result } from "@/lib/utils/result";
import type { DidDocumentResolver } from "@atcute/identity-resolver";
import {
···
return { ok: true, data: record.value };
};
export const didDocResolver: DidDocumentResolver =
new CompositeDidDocumentResolver({
methods: {
···
atUriAuthoritySchema,
nsidSchema,
} from "@/lib/types/atproto";
+
import type {
+
ComAtprotoRepoGetRecordResponse} from "@/lib/types/lexicon/com.atproto.repo.getRecord";
+
import {
+
comAtprotoRepoGetRecordResponseSchema,
+
} from "@/lib/types/lexicon/com.atproto.repo.getRecord";
import type { Result } from "@/lib/utils/result";
import type { DidDocumentResolver } from "@atcute/identity-resolver";
import {
···
return { ok: true, data: record.value };
};
+
export const getCommitFromFullAtUri = async ({
+
authority,
+
collection,
+
rKey,
+
}: AtUri): Promise<Result<ComAtprotoRepoGetRecordResponse, unknown>> => {
+
const didDocResult = await resolveDidDoc(authority);
+
if (!didDocResult.ok) return { ok: false, error: didDocResult.error };
+
+
if (!collection || !rKey)
+
return {
+
ok: false,
+
error: "No rkey or collection found in provided AtUri object",
+
};
+
+
const { service: services } = didDocResult.data;
+
if (!services)
+
return {
+
ok: false,
+
error: { message: "Resolved DID document has no service field." },
+
};
+
+
const pdsService = services.find(
+
(service) =>
+
service.id === "#atproto_pds" &&
+
service.type === "AtprotoPersonalDataServer",
+
);
+
+
if (!pdsService)
+
return {
+
ok: false,
+
error: {
+
message:
+
"Resolved DID document has no PDS service listed in the document.",
+
},
+
};
+
+
const pdsEndpointRecord = pdsService.serviceEndpoint;
+
let pdsEndpointUrl;
+
try {
+
// @ts-expect-error yes, we are coercing something that is explicitly not a string into a string, but in this case we want to be specific. only serviceEndpoints with valid atproto pds URLs should be allowed.
+
pdsEndpointUrl = new URL(pdsEndpointRecord).origin;
+
} catch (err) {
+
return { ok: false, error: err };
+
}
+
const req = new Request(
+
`${pdsEndpointUrl}/xrpc/com.atproto.repo.getRecord?repo=${didDocResult.data.id}&collection=${collection}&rkey=${rKey}`,
+
);
+
+
const res = await fetch(req);
+
const data: unknown = await res.json();
+
+
const {
+
success: responseParseSuccess,
+
error: responseParseError,
+
data: record,
+
} = comAtprotoRepoGetRecordResponseSchema.safeParse(data);
+
if (!responseParseSuccess) {
+
return { ok: false, error: responseParseError };
+
}
+
return { ok: true, data: record };
+
};
+
export const didDocResolver: DidDocumentResolver =
new CompositeDidDocumentResolver({
methods: {
+1 -1
assets/oauth-client-metadata.json
···
"client_name": "Gemstone",
"client_uri": "https://app.gmstn.systems",
"redirect_uris": [
-
"systems.gmstn.app:/oauth/callback"
],
"scope": "atproto transition:generic",
"token_endpoint_auth_method": "none",
···
"client_name": "Gemstone",
"client_uri": "https://app.gmstn.systems",
"redirect_uris": [
+
"systems.gmstn.app:/login/"
],
"scope": "atproto transition:generic",
"token_endpoint_auth_method": "none",
+19 -3
src/providers/authed/HandshakesProvider.tsx
···
channelsMap.set(key, existingGroup);
});
// TODO: move this to own query hook
const handshakeQueries = useQueries({
queries: channelsMap
···
queryFn: () =>
handshakesQueryFn({
channel: channelObjs[0].channel,
-
memberships: memberships.map(
-
({ membership }) => membership,
-
),
oauth,
}),
staleTime: Infinity,
···
channelsMap.set(key, existingGroup);
});
+
const membershipsMap = new Map<
+
AtUri,
+
SystemsGmstnDevelopmentChannelMembership
+
>();
+
channels.forEach((channelData) => {
+
const membership = memberships.find(
+
(membershipData) =>
+
membershipData.channelAtUri.rKey ===
+
channelData.channelAtUri.rKey,
+
);
+
if (!membership) return;
+
membershipsMap.set(channelData.channelAtUri, membership.membership);
+
});
+
// TODO: move this to own query hook
const handshakeQueries = useQueries({
queries: channelsMap
···
queryFn: () =>
handshakesQueryFn({
channel: channelObjs[0].channel,
+
memberships: channelObjs
+
.map((channelObj) =>
+
membershipsMap.get(channelObj.channelAtUri),
+
)
+
.filter((val) => val !== undefined),
oauth,
}),
staleTime: Infinity,
+3 -1
package.json
···
"dev:web": "expo start --web",
"dev:android": "expo start --android",
"dev:ios": "expo start --ios",
-
"dev:expo": "expo start"
},
"dependencies": {
"@atcute/atproto": "^3.1.7",
···
"dev:web": "expo start --web",
"dev:android": "expo start --android",
"dev:ios": "expo start --ios",
+
"dev:expo": "expo start",
+
"export:web": "expo export -p web",
+
"export:web:serve": "expo serve"
},
"dependencies": {
"@atcute/atproto": "^3.1.7",
-1
src/providers/authed/ChannelsProvider.tsx
···
// TODO: move this to own query hook
const channelsQueries = useQueries({
queries: memberships.map((membershipObjects) => {
-
return {
enabled: !membershipsInitialising,
queryKey: ["channel", membershipObjects.membership.channel.uri],
···
// TODO: move this to own query hook
const channelsQueries = useQueries({
queries: memberships.map((membershipObjects) => {
return {
enabled: !membershipsInitialising,
queryKey: ["channel", membershipObjects.membership.channel.uri],
+7 -5
src/components/Chat/index.tsx
···
export const Chat = ({ channelAtUri }: { channelAtUri: AtUri }) => {
const [inputText, setInputText] = useState("");
-
const { messages, sendMessageToChannel, isConnected } =
-
useChannel(channelAtUri);
const record = useChannelRecordByAtUriObject(channelAtUri);
const { semantic } = useCurrentPalette();
const { typography, atoms } = useFacet();
const handleSend = () => {
if (inputText.trim()) {
···
}
};
-
const { isLoading } = useProfile();
-
if (!record)
return (
<View>
<Text>
-
Something has gone wrong. Could not resolve channel record
from given at:// URI.
</Text>
</View>
···
export const Chat = ({ channelAtUri }: { channelAtUri: AtUri }) => {
const [inputText, setInputText] = useState("");
const record = useChannelRecordByAtUriObject(channelAtUri);
const { semantic } = useCurrentPalette();
const { typography, atoms } = useFacet();
+
const channel = useChannel(channelAtUri);
+
const { isLoading } = useProfile();
+
+
if (!channel) return <></>;
+
+
const { messages, sendMessageToChannel, isConnected } = channel;
const handleSend = () => {
if (inputText.trim()) {
···
}
};
if (!record)
return (
<View>
<Text>
+
Something has gone wrong.Could not resolve channel record
from given at:// URI.
</Text>
</View>
+17 -9
src/lib/hooks/useChannel.ts
···
const { sessionInfo, socket } = findChannelSession(channel);
useEffect(() => {
-
if (!sessionInfo)
-
throw new Error(
"Channel did not resolve to a valid sessionInfo object.",
);
-
if (!socket)
-
throw new Error(
"Session info did not resolve to a valid websocket connection. This should not happen and is likely a bug. Check the sessions map object.",
);
// attach handlers here
···
};
}, [socket, sessionInfo, channel]);
-
if (!oAuthSession) throw new Error("No OAuth session");
-
if (!sessionInfo)
-
throw new Error(
"Channel did not resolve to a valid sessionInfo object.",
);
-
if (!socket)
-
throw new Error(
"Session info did not resolve to a valid websocket connection. This should not happen and is likely a bug. Check the sessions map object.",
);
const channelStringified = atUriToString(channel);
···
const { sessionInfo, socket } = findChannelSession(channel);
useEffect(() => {
+
if (!sessionInfo) {
+
console.warn(
"Channel did not resolve to a valid sessionInfo object.",
);
+
return;
+
}
+
if (!socket) {
+
console.warn(
"Session info did not resolve to a valid websocket connection. This should not happen and is likely a bug. Check the sessions map object.",
);
+
return;
+
}
// attach handlers here
···
};
}, [socket, sessionInfo, channel]);
+
if (!oAuthSession) {console.warn("No OAuth session"); return }
+
if (!sessionInfo) {
+
console.warn(
"Channel did not resolve to a valid sessionInfo object.",
);
+
return;
+
}
+
if (!socket) {
+
console.warn(
"Session info did not resolve to a valid websocket connection. This should not happen and is likely a bug. Check the sessions map object.",
);
+
return;
+
}
const channelStringified = atUriToString(channel);
+1 -1
src/lib/utils/gmstn.ts
···
agent: Agent;
}): Promise<Result<undefined, string>> => {
const now = new Date();
-
const rkey = TID.create(now.getTime(), Math.random());
const record: Omit<SystemsGmstnDevelopmentChannelInvite, "$type"> = {
// @ts-expect-error we want to explicitly use the ISO string variant
···
agent: Agent;
}): Promise<Result<undefined, string>> => {
const now = new Date();
+
const rkey = TID.create(now.getTime() * 1_000, Math.random());
const record: Omit<SystemsGmstnDevelopmentChannelInvite, "$type"> = {
// @ts-expect-error we want to explicitly use the ISO string variant
+1 -1
src/lib/utils/atproto/oauth.web.ts
···
} from "@atproto/oauth-client-browser";
import type { ExpoOAuthClientOptions } from "@atproto/oauth-client-expo";
import { ExpoOAuthClient as PbcWebExpoOAuthClient } from "@atproto/oauth-client-expo";
-
import oAuthMetadata from "../../../../assets/oauth-client-metadata.json";
import { __DEV__loopbackOAuthMetadata } from "@/lib/consts";
// suuuuuch a hack holy shit
···
} from "@atproto/oauth-client-browser";
import type { ExpoOAuthClientOptions } from "@atproto/oauth-client-expo";
import { ExpoOAuthClient as PbcWebExpoOAuthClient } from "@atproto/oauth-client-expo";
+
import oAuthMetadata from "../../../../public/oauth-client-metadata.json";
import { __DEV__loopbackOAuthMetadata } from "@/lib/consts";
// suuuuuch a hack holy shit
+4 -6
src/components/Invites/index.tsx
···
useConstellationInvitesQuery(session);
const queryClient = useQueryClient();
-
const queryKeysToInvalidate = constellationInvitesQueryKey.concat([
-
"membership",
-
session.did,
-
]);
-
const { mutate: mutateInvites, error: inviteMutationError } = useMutation({
mutationFn: async (state: "accepted" | "rejected") => {
const inviteCommitRes = await getCommitFromFullAtUri(inviteAtUri);
···
},
onSuccess: async () => {
await queryClient.invalidateQueries({
-
queryKey: queryKeysToInvalidate,
});
},
onError: () => {
···
useConstellationInvitesQuery(session);
const queryClient = useQueryClient();
const { mutate: mutateInvites, error: inviteMutationError } = useMutation({
mutationFn: async (state: "accepted" | "rejected") => {
const inviteCommitRes = await getCommitFromFullAtUri(inviteAtUri);
···
},
onSuccess: async () => {
await queryClient.invalidateQueries({
+
queryKey: ["membership", session.did],
+
});
+
await queryClient.invalidateQueries({
+
queryKey: constellationInvitesQueryKey,
});
},
onError: () => {
+82 -23
src/components/Auth/Login.web.tsx
···
import { useOAuthSetter, useOAuthValue } from "@/providers/OAuthProvider";
import { Agent } from "@atproto/api";
import { useState } from "react";
-
import { Button, StyleSheet, TextInput, View } from "react-native";
export const Login = () => {
const [atprotoHandle, setAtprotoHandle] = useState("");
const oAuth = useOAuthValue();
const setOAuth = useOAuthSetter();
···
};
return (
-
<View>
-
<TextInput
-
style={styles.input}
-
value={atprotoHandle}
-
onChangeText={setAtprotoHandle}
-
placeholder="alice.bsky.social"
-
onSubmitEditing={handleSubmit}
-
/>
-
<Button title="Log in with your PDS ->" onPress={handleSubmit} />
</View>
);
};
-
-
const styles = StyleSheet.create({
-
input: {
-
flex: 1,
-
borderWidth: 1,
-
borderColor: "#ccc",
-
borderRadius: 8,
-
paddingHorizontal: 12,
-
paddingVertical: 8,
-
marginRight: 8,
-
fontSize: 16,
-
},
-
});
···
+
import { GmstnLogoColor } from "@/components/icons/gmstn/GmstnLogoColor";
+
import { Text } from "@/components/primitives/Text";
+
import { useFacet } from "@/lib/facet";
+
import { lighten } from "@/lib/facet/src/lib/colors";
import { useOAuthSetter, useOAuthValue } from "@/providers/OAuthProvider";
+
import { useCurrentPalette } from "@/providers/ThemeProvider";
import { Agent } from "@atproto/api";
+
import { ArrowRight } from "lucide-react-native";
import { useState } from "react";
+
import { Pressable, TextInput, View } from "react-native";
export const Login = () => {
+
const { semantic } = useCurrentPalette();
+
const { atoms, typography } = useFacet();
const [atprotoHandle, setAtprotoHandle] = useState("");
const oAuth = useOAuthValue();
const setOAuth = useOAuthSetter();
···
};
return (
+
<View
+
style={{
+
flex: 1,
+
flexDirection: "column",
+
alignItems: "center",
+
justifyContent: "center",
+
gap: 16,
+
}}
+
>
+
<View style={{ alignItems: "center" }}>
+
<View style={{ padding: 8, paddingLeft: 12, paddingTop: 12 }}>
+
<GmstnLogoColor height={36} width={36} />
+
</View>
+
<Text
+
style={[
+
typography.sizes.xl,
+
typography.weights.byName.medium,
+
]}
+
>
+
Gemstone
+
</Text>
+
</View>
+
<View style={{ gap: 10 }}>
+
<TextInput
+
style={[{
+
flex: 1,
+
borderWidth: 1,
+
borderColor: semantic.border,
+
borderRadius: atoms.radii.lg,
+
paddingHorizontal: 14,
+
paddingVertical: 12,
+
marginRight: 8,
+
fontSize: 16,
+
color: semantic.text
+
}, typography.weights.byName.light]}
+
value={atprotoHandle}
+
onChangeText={setAtprotoHandle}
+
placeholder="alice.bsky.social"
+
onSubmitEditing={handleSubmit}
+
placeholderTextColor={semantic.textPlaceholder}
+
/>
+
<Pressable onPress={handleSubmit}>
+
{({ hovered }) => (
+
<View
+
style={{
+
backgroundColor: hovered
+
? lighten(semantic.primary, 7)
+
: semantic.primary,
+
flexDirection: "row",
+
gap: 4,
+
alignItems: "center",
+
justifyContent: "center",
+
paddingVertical: 10,
+
borderRadius: atoms.radii.lg,
+
}}
+
>
+
<Text
+
style={[
+
{ color: semantic.textInverse },
+
typography.weights.byName.normal,
+
]}
+
>
+
Log in with ATProto
+
</Text>
+
<ArrowRight
+
height={16}
+
width={16}
+
color={semantic.textInverse}
+
/>
+
</View>
+
)}
+
</Pressable>
+
</View>
</View>
);
};