1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-07-31 09:24:31 +03:00

WIP my account page

This commit is contained in:
Quentin Gliech
2023-04-26 19:25:18 +02:00
parent 415d06f209
commit f62d045b8c
5 changed files with 239 additions and 65 deletions

View File

@ -25,6 +25,9 @@ const ADD_EMAIL_MUTATION = graphql(/* GraphQL */ `
mutation AddEmail($userId: ID!, $email: String!) { mutation AddEmail($userId: ID!, $email: String!) {
addEmail(input: { userId: $userId, email: $email }) { addEmail(input: { userId: $userId, email: $email }) {
status status
user {
id
}
email { email {
id id
...UserEmail_email ...UserEmail_email

View File

@ -14,8 +14,7 @@
import { atom, useAtomValue, useSetAtom } from "jotai"; import { atom, useAtomValue, useSetAtom } from "jotai";
import { atomWithQuery } from "jotai-urql"; import { atomWithQuery } from "jotai-urql";
import { atomFamily } from "jotai/utils"; import { atomFamily, atomWithDefault } from "jotai/utils";
import deepEqual from "fast-deep-equal";
import { graphql } from "../gql"; import { graphql } from "../gql";
import { useTransition } from "react"; import { useTransition } from "react";
@ -24,10 +23,17 @@ import UserEmail from "./UserEmail";
import BlockList from "./BlockList"; import BlockList from "./BlockList";
const QUERY = graphql(/* GraphQL */ ` const QUERY = graphql(/* GraphQL */ `
query UserEmailListQuery($userId: ID!, $first: Int!, $after: String) { query UserEmailListQuery(
$userId: ID!
$first: Int
$after: String
$last: Int
$before: String
) {
user(id: $userId) { user(id: $userId) {
__typename
id id
emails(first: $first, after: $after) { emails(first: $first, after: $after, last: $last, before: $before) {
edges { edges {
cursor cursor
node { node {
@ -35,8 +41,11 @@ const QUERY = graphql(/* GraphQL */ `
...UserEmail_email ...UserEmail_email
} }
} }
totalCount
pageInfo { pageInfo {
hasNextPage hasNextPage
hasPreviousPage
startCursor
endCursor endCursor
} }
} }
@ -44,64 +53,145 @@ const QUERY = graphql(/* GraphQL */ `
} }
`); `);
const emailPageResultFamily = atomFamily( type ForwardPagination = {
({ userId, after }: { userId: string; after: string | null }) => first: int;
atomWithQuery({ after: string | null;
};
type BackwardPagination = {
last: int;
before: string | null;
};
type Pagination = ForwardPagination | BackwardPagination;
const isForwardPagination = (
pagination: Pagination
): pagination is ForwardPagination => {
return pagination.hasOwnProperty("first");
};
const isBackwardPagination = (
pagination: Pagination
): pagination is BackwardPagination => {
return pagination.hasOwnProperty("last");
};
const pageSize = atom(6);
const currentPagination = atomWithDefault<Pagination>((get) => ({
first: get(pageSize),
after: null,
}));
const emailPageResultFamily = atomFamily((userId: string) => {
const emailPageResult = atomWithQuery({
query: QUERY, query: QUERY,
getVariables: () => ({ userId, first: 5, after }), getVariables: (get) => ({ userId, ...get(currentPagination) }),
}), });
deepEqual return emailPageResult;
); });
const emailPageListFamily = atomFamily((_userId: string) => const nextPagePaginationFamily = atomFamily((userId: string) => {
atom([null as string | null]) const nextPagePagination = atom(
); async (get): Promise<ForwardPagination | null> => {
// If we are paginating backwards, we can assume there is a next page
const pagination = get(currentPagination);
const hasProbablyNextPage =
isBackwardPagination(pagination) && pagination.before !== null;
const emailNextPageFamily = atomFamily((userId: string) => const result = await get(emailPageResultFamily(userId));
atom(null, (get, set, after: string) => { const pageInfo = result.data?.user?.emails?.pageInfo;
const currentList = get(emailPageListFamily(userId)); if (pageInfo?.hasNextPage || hasProbablyNextPage) {
set(emailPageListFamily(userId), [...currentList, after]); return {
}) first: get(pageSize),
); after: pageInfo?.endCursor ?? null,
};
}
const emailPageFamily = atomFamily((userId: string) => return null;
atom(async (get) => { }
const list = get(emailPageListFamily(userId));
return await Promise.all(
list.map((after) => get(emailPageResultFamily({ userId, after })))
); );
}) return nextPagePagination;
); });
const prevPagePaginationFamily = atomFamily((userId: string) => {
const prevPagePagination = atom(
async (get): Promise<BackwardPagination | null> => {
// If we are paginating forwards, we can assume there is a previous page
const pagination = get(currentPagination);
const hasProbablyPreviousPage =
isForwardPagination(pagination) && pagination.after !== null;
const result = await get(emailPageResultFamily(userId));
const pageInfo = result.data?.user?.emails?.pageInfo;
if (pageInfo?.hasPreviousPage || hasProbablyPreviousPage) {
return {
last: get(pageSize),
before: pageInfo?.startCursor ?? null,
};
}
return null;
}
);
return prevPagePagination;
});
const UserEmailList: React.FC<{ userId: string }> = ({ userId }) => { const UserEmailList: React.FC<{ userId: string }> = ({ userId }) => {
const [pending, startTransition] = useTransition(); const [pending, startTransition] = useTransition();
const result = useAtomValue(emailPageFamily(userId)); const result = useAtomValue(emailPageResultFamily(userId));
const setLoadNextPage = useSetAtom(emailNextPageFamily(userId)); const setPagination = useSetAtom(currentPagination);
const endPageInfo = result[result.length - 1]?.data?.user?.emails?.pageInfo; const nextPagePagination = useAtomValue(nextPagePaginationFamily(userId));
const prevPagePagination = useAtomValue(prevPagePaginationFamily(userId));
const loadNextPage = () => { const paginate = (pagination: Pagination) => {
if (endPageInfo?.hasNextPage && endPageInfo.endCursor) {
const cursor = endPageInfo.endCursor;
startTransition(() => { startTransition(() => {
setLoadNextPage(cursor); setPagination(pagination);
}); });
}
}; };
return ( return (
<BlockList> <div>
{result.flatMap( <div className="grid items-center grid-cols-3 gap-2 mb-2">
(page) => {prevPagePagination ? (
page.data?.user?.emails?.edges?.map((edge) => ( <Button
<UserEmail email={edge.node} key={edge.cursor} /> compact
)) || [] disabled={pending}
)} ghost
{endPageInfo?.hasNextPage && ( onClick={() => paginate(prevPagePagination)}
<Button compact ghost onClick={loadNextPage}> >
{pending ? "Loading..." : "Load more"} Previous
</Button>
) : (
<Button compact disabled ghost>
Previous
</Button> </Button>
)} )}
<div className="text-center">
Total: {result.data?.user?.emails?.totalCount}
</div>
{nextPagePagination ? (
<Button
compact
disabled={pending}
ghost
onClick={() => paginate(nextPagePagination)}
>
Next
</Button>
) : (
<Button compact disabled ghost>
Next
</Button>
)}
</div>
<BlockList>
{result.data?.user?.emails?.edges?.map((edge) => (
<UserEmail email={edge.node} key={edge.cursor} />
))}
</BlockList> </BlockList>
</div>
); );
}; };

View File

@ -13,7 +13,7 @@ import { TypedDocumentNode as DocumentNode } from "@graphql-typed-document-node/
* Therefore it is highly recommended to use the babel or swc plugin for production. * Therefore it is highly recommended to use the babel or swc plugin for production.
*/ */
const documents = { const documents = {
"\n mutation AddEmail($userId: ID!, $email: String!) {\n addEmail(input: { userId: $userId, email: $email }) {\n status\n email {\n id\n ...UserEmail_email\n }\n }\n }\n": "\n mutation AddEmail($userId: ID!, $email: String!) {\n addEmail(input: { userId: $userId, email: $email }) {\n status\n user {\n id\n }\n email {\n id\n ...UserEmail_email\n }\n }\n }\n":
types.AddEmailDocument, types.AddEmailDocument,
"\n fragment BrowserSession_session on BrowserSession {\n id\n createdAt\n lastAuthentication {\n id\n createdAt\n }\n }\n": "\n fragment BrowserSession_session on BrowserSession {\n id\n createdAt\n lastAuthentication {\n id\n createdAt\n }\n }\n":
types.BrowserSession_SessionFragmentDoc, types.BrowserSession_SessionFragmentDoc,
@ -29,7 +29,7 @@ const documents = {
types.OAuth2SessionList_UserFragmentDoc, types.OAuth2SessionList_UserFragmentDoc,
"\n fragment UserEmail_email on UserEmail {\n id\n email\n createdAt\n confirmedAt\n }\n": "\n fragment UserEmail_email on UserEmail {\n id\n email\n createdAt\n confirmedAt\n }\n":
types.UserEmail_EmailFragmentDoc, types.UserEmail_EmailFragmentDoc,
"\n query UserEmailListQuery($userId: ID!, $first: Int!, $after: String) {\n user(id: $userId) {\n id\n emails(first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n ...UserEmail_email\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n": "\n query UserEmailListQuery(\n $userId: ID!\n $first: Int\n $after: String\n $last: Int\n $before: String\n ) {\n user(id: $userId) {\n __typename\n id\n emails(first: $first, after: $after, last: $last, before: $before) {\n edges {\n cursor\n node {\n id\n ...UserEmail_email\n }\n }\n totalCount\n pageInfo {\n hasNextPage\n hasPreviousPage\n startCursor\n endCursor\n }\n }\n }\n }\n":
types.UserEmailListQueryDocument, types.UserEmailListQueryDocument,
"\n query CurrentUserQuery {\n viewer {\n ... on User {\n __typename\n id\n }\n }\n }\n": "\n query CurrentUserQuery {\n viewer {\n ... on User {\n __typename\n id\n }\n }\n }\n":
types.CurrentUserQueryDocument, types.CurrentUserQueryDocument,
@ -61,8 +61,8 @@ export function graphql(source: string): unknown;
* The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/ */
export function graphql( export function graphql(
source: "\n mutation AddEmail($userId: ID!, $email: String!) {\n addEmail(input: { userId: $userId, email: $email }) {\n status\n email {\n id\n ...UserEmail_email\n }\n }\n }\n" source: "\n mutation AddEmail($userId: ID!, $email: String!) {\n addEmail(input: { userId: $userId, email: $email }) {\n status\n user {\n id\n }\n email {\n id\n ...UserEmail_email\n }\n }\n }\n"
): (typeof documents)["\n mutation AddEmail($userId: ID!, $email: String!) {\n addEmail(input: { userId: $userId, email: $email }) {\n status\n email {\n id\n ...UserEmail_email\n }\n }\n }\n"]; ): (typeof documents)["\n mutation AddEmail($userId: ID!, $email: String!) {\n addEmail(input: { userId: $userId, email: $email }) {\n status\n user {\n id\n }\n email {\n id\n ...UserEmail_email\n }\n }\n }\n"];
/** /**
* The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/ */
@ -109,8 +109,8 @@ export function graphql(
* The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/ */
export function graphql( export function graphql(
source: "\n query UserEmailListQuery($userId: ID!, $first: Int!, $after: String) {\n user(id: $userId) {\n id\n emails(first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n ...UserEmail_email\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n" source: "\n query UserEmailListQuery(\n $userId: ID!\n $first: Int\n $after: String\n $last: Int\n $before: String\n ) {\n user(id: $userId) {\n __typename\n id\n emails(first: $first, after: $after, last: $last, before: $before) {\n edges {\n cursor\n node {\n id\n ...UserEmail_email\n }\n }\n totalCount\n pageInfo {\n hasNextPage\n hasPreviousPage\n startCursor\n endCursor\n }\n }\n }\n }\n"
): (typeof documents)["\n query UserEmailListQuery($userId: ID!, $first: Int!, $after: String) {\n user(id: $userId) {\n id\n emails(first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n ...UserEmail_email\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n"]; ): (typeof documents)["\n query UserEmailListQuery(\n $userId: ID!\n $first: Int\n $after: String\n $last: Int\n $before: String\n ) {\n user(id: $userId) {\n __typename\n id\n emails(first: $first, after: $after, last: $last, before: $before) {\n edges {\n cursor\n node {\n id\n ...UserEmail_email\n }\n }\n totalCount\n pageInfo {\n hasNextPage\n hasPreviousPage\n startCursor\n endCursor\n }\n }\n }\n }\n"];
/** /**
* The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/ */

View File

@ -587,6 +587,7 @@ export type AddEmailMutation = {
addEmail: { addEmail: {
__typename?: "AddEmailPayload"; __typename?: "AddEmailPayload";
status: AddEmailStatus; status: AddEmailStatus;
user: { __typename?: "User"; id: string };
email: { __typename?: "UserEmail"; id: string } & { email: { __typename?: "UserEmail"; id: string } & {
" $fragmentRefs"?: { UserEmail_EmailFragment: UserEmail_EmailFragment }; " $fragmentRefs"?: { UserEmail_EmailFragment: UserEmail_EmailFragment };
}; };
@ -688,17 +689,20 @@ export type UserEmail_EmailFragment = {
export type UserEmailListQueryQueryVariables = Exact<{ export type UserEmailListQueryQueryVariables = Exact<{
userId: Scalars["ID"]; userId: Scalars["ID"];
first: Scalars["Int"]; first?: InputMaybe<Scalars["Int"]>;
after?: InputMaybe<Scalars["String"]>; after?: InputMaybe<Scalars["String"]>;
last?: InputMaybe<Scalars["Int"]>;
before?: InputMaybe<Scalars["String"]>;
}>; }>;
export type UserEmailListQueryQuery = { export type UserEmailListQueryQuery = {
__typename?: "Query"; __typename?: "Query";
user?: { user?: {
__typename?: "User"; __typename: "User";
id: string; id: string;
emails: { emails: {
__typename?: "UserEmailConnection"; __typename?: "UserEmailConnection";
totalCount: number;
edges: Array<{ edges: Array<{
__typename?: "UserEmailEdge"; __typename?: "UserEmailEdge";
cursor: string; cursor: string;
@ -711,6 +715,8 @@ export type UserEmailListQueryQuery = {
pageInfo: { pageInfo: {
__typename?: "PageInfo"; __typename?: "PageInfo";
hasNextPage: boolean; hasNextPage: boolean;
hasPreviousPage: boolean;
startCursor?: string | null;
endCursor?: string | null; endCursor?: string | null;
}; };
}; };
@ -1294,6 +1300,16 @@ export const AddEmailDocument = {
kind: "SelectionSet", kind: "SelectionSet",
selections: [ selections: [
{ kind: "Field", name: { kind: "Name", value: "status" } }, { kind: "Field", name: { kind: "Name", value: "status" } },
{
kind: "Field",
name: { kind: "Name", value: "user" },
selectionSet: {
kind: "SelectionSet",
selections: [
{ kind: "Field", name: { kind: "Name", value: "id" } },
],
},
},
{ {
kind: "Field", kind: "Field",
name: { kind: "Name", value: "email" }, name: { kind: "Name", value: "email" },
@ -1358,11 +1374,8 @@ export const UserEmailListQueryDocument = {
kind: "Variable", kind: "Variable",
name: { kind: "Name", value: "first" }, name: { kind: "Name", value: "first" },
}, },
type: {
kind: "NonNullType",
type: { kind: "NamedType", name: { kind: "Name", value: "Int" } }, type: { kind: "NamedType", name: { kind: "Name", value: "Int" } },
}, },
},
{ {
kind: "VariableDefinition", kind: "VariableDefinition",
variable: { variable: {
@ -1371,6 +1384,19 @@ export const UserEmailListQueryDocument = {
}, },
type: { kind: "NamedType", name: { kind: "Name", value: "String" } }, type: { kind: "NamedType", name: { kind: "Name", value: "String" } },
}, },
{
kind: "VariableDefinition",
variable: { kind: "Variable", name: { kind: "Name", value: "last" } },
type: { kind: "NamedType", name: { kind: "Name", value: "Int" } },
},
{
kind: "VariableDefinition",
variable: {
kind: "Variable",
name: { kind: "Name", value: "before" },
},
type: { kind: "NamedType", name: { kind: "Name", value: "String" } },
},
], ],
selectionSet: { selectionSet: {
kind: "SelectionSet", kind: "SelectionSet",
@ -1391,6 +1417,7 @@ export const UserEmailListQueryDocument = {
selectionSet: { selectionSet: {
kind: "SelectionSet", kind: "SelectionSet",
selections: [ selections: [
{ kind: "Field", name: { kind: "Name", value: "__typename" } },
{ kind: "Field", name: { kind: "Name", value: "id" } }, { kind: "Field", name: { kind: "Name", value: "id" } },
{ {
kind: "Field", kind: "Field",
@ -1412,6 +1439,22 @@ export const UserEmailListQueryDocument = {
name: { kind: "Name", value: "after" }, name: { kind: "Name", value: "after" },
}, },
}, },
{
kind: "Argument",
name: { kind: "Name", value: "last" },
value: {
kind: "Variable",
name: { kind: "Name", value: "last" },
},
},
{
kind: "Argument",
name: { kind: "Name", value: "before" },
value: {
kind: "Variable",
name: { kind: "Name", value: "before" },
},
},
], ],
selectionSet: { selectionSet: {
kind: "SelectionSet", kind: "SelectionSet",
@ -1449,6 +1492,10 @@ export const UserEmailListQueryDocument = {
], ],
}, },
}, },
{
kind: "Field",
name: { kind: "Name", value: "totalCount" },
},
{ {
kind: "Field", kind: "Field",
name: { kind: "Name", value: "pageInfo" }, name: { kind: "Name", value: "pageInfo" },
@ -1459,6 +1506,14 @@ export const UserEmailListQueryDocument = {
kind: "Field", kind: "Field",
name: { kind: "Name", value: "hasNextPage" }, name: { kind: "Name", value: "hasNextPage" },
}, },
{
kind: "Field",
name: { kind: "Name", value: "hasPreviousPage" },
},
{
kind: "Field",
name: { kind: "Name", value: "startCursor" },
},
{ {
kind: "Field", kind: "Field",
name: { kind: "Name", value: "endCursor" }, name: { kind: "Name", value: "endCursor" },

View File

@ -16,8 +16,34 @@ import { createClient, fetchExchange } from "@urql/core";
import { cacheExchange } from "@urql/exchange-graphcache"; import { cacheExchange } from "@urql/exchange-graphcache";
import schema from "./gql/schema"; import schema from "./gql/schema";
import type { MutationAddEmailArgs } from "./gql/graphql";
export const client = createClient({ export const client = createClient({
url: "/graphql", url: "/graphql",
exchanges: [cacheExchange({ schema }), fetchExchange], // XXX: else queries don't refetch on cache invalidation for some reason
requestPolicy: "cache-and-network",
exchanges: [
cacheExchange({
schema,
updates: {
Mutation: {
addEmail: (result, args: MutationAddEmailArgs, cache, _info) => {
const key = cache.keyOfEntity({
__typename: "User",
id: args.input.userId,
});
// Invalidate the emails field on the User object so that it gets refetched
cache
.inspectFields(key)
.filter((field) => field.fieldName === "emails")
.forEach((field) => {
cache.invalidate(key, field.fieldName, field.arguments);
});
},
},
},
}),
fetchExchange,
],
}); });