Skip to content
This repository has been archived by the owner on Sep 10, 2024. It is now read-only.

Replace jotai-urql with just urql #2351

Merged
merged 4 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion frontend/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
}
},
"app_sessions_list": {
"error": "Failed to load app sessions",
"heading": "Apps"
},
"browser_session_details": {
Expand Down
15 changes: 14 additions & 1 deletion frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@
"jotai": "^2.6.4",
"jotai-devtools": "^0.7.1",
"jotai-location": "^0.5.2",
"jotai-urql": "^0.7.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-i18next": "^14.0.5",
"ua-parser-js": "^1.0.37"
"ua-parser-js": "^1.0.37",
"urql": "^4.0.6"
},
"devDependencies": {
"@graphql-codegen/cli": "^5.0.2",
Expand Down
123 changes: 0 additions & 123 deletions frontend/src/atoms.ts
Original file line number Diff line number Diff line change
@@ -1,123 +0,0 @@
// Copyright 2023 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { AnyVariables, CombinedError, OperationContext } from "@urql/core";
import { atom, WritableAtom } from "jotai";
import { useHydrateAtoms } from "jotai/utils";
import { AtomWithQuery, atomWithQuery, clientAtom } from "jotai-urql";
import type { ReactElement } from "react";

import { graphql } from "./gql";
import { client } from "./graphql";
import { err, ok, Result } from "./result";

export type GqlResult<T> = Result<T, CombinedError>;
export type GqlAtom<T> = WritableAtom<
Promise<GqlResult<T>>,
[context?: Partial<OperationContext>],
void
>;

/**
* Map the result of a query atom to a new value, making it a GqlResult
*
* @param queryAtom: An atom got from atomWithQuery
* @param mapper: A function that takes the data from the query and returns a new value
*/
export const mapQueryAtom = <Data, Variables extends AnyVariables, NewData>(
queryAtom: AtomWithQuery<Data, Variables>,
mapper: (data: Data) => NewData,
): GqlAtom<NewData> => {
return atom(
async (get): Promise<GqlResult<NewData>> => {
const result = await get(queryAtom);
if (result.error) {
return err(result.error);
}

if (result.data === undefined) {
throw new Error("Query result is undefined");
}

return ok(mapper(result.data));
},

(_get, set, context) => {
set(queryAtom, context);
},
);
};

export const HydrateAtoms: React.FC<{ children: ReactElement }> = ({
children,
}) => {
useHydrateAtoms([[clientAtom, client]]);
return children;
};

const CURRENT_VIEWER_QUERY = graphql(/* GraphQL */ `
query CurrentViewerQuery {
viewer {
__typename
... on User {
id
}

... on Anonymous {
id
}
}
}
`);

const currentViewerAtom = atomWithQuery({ query: CURRENT_VIEWER_QUERY });

export const currentUserIdAtom: GqlAtom<string | null> = mapQueryAtom(
currentViewerAtom,
(data) => {
if (data.viewer.__typename === "User") {
return data.viewer.id;
}
return null;
},
);

const CURRENT_VIEWER_SESSION_QUERY = graphql(/* GraphQL */ `
query CurrentViewerSessionQuery {
viewerSession {
__typename
... on BrowserSession {
id
}

... on Anonymous {
id
}
}
}
`);

const currentViewerSessionAtom = atomWithQuery({
query: CURRENT_VIEWER_SESSION_QUERY,
});

export const currentBrowserSessionIdAtom: GqlAtom<string | null> = mapQueryAtom(
currentViewerSessionAtom,
(data) => {
if (data.viewerSession.__typename === "BrowserSession") {
return data.viewerSession.id;
}
return null;
},
);
34 changes: 5 additions & 29 deletions frontend/src/components/BrowserSession.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,9 @@
// limitations under the License.

import { parseISO } from "date-fns";
import { atom, useSetAtom } from "jotai";
import { atomFamily } from "jotai/utils";
import { atomWithMutation } from "jotai-urql";
import { useCallback } from "react";
import { useMutation } from "urql";

import { currentBrowserSessionIdAtom, currentUserIdAtom } from "../atoms";
import { FragmentType, graphql, useFragment } from "../gql";
import {
parseUserAgent,
Expand Down Expand Up @@ -56,39 +53,18 @@
}
`);

export const endBrowserSessionFamily = atomFamily((id: string) => {
const endSession = atomWithMutation(END_SESSION_MUTATION);

// A proxy atom which pre-sets the id variable in the mutation
const endSessionAtom = atom(
(get) => get(endSession),
(get, set) => set(endSession, { id }),
);

return endSessionAtom;
});

export const useEndBrowserSession = (
sessionId: string,
isCurrent: boolean,
): (() => Promise<void>) => {
const endSession = useSetAtom(endBrowserSessionFamily(sessionId));

// Pull those atoms to reset them when the current session is ended
const currentUserId = useSetAtom(currentUserIdAtom);
const currentBrowserSessionId = useSetAtom(currentBrowserSessionIdAtom);
const [, endSession] = useMutation(END_SESSION_MUTATION);

Check warning on line 60 in frontend/src/components/BrowserSession.tsx

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/BrowserSession.tsx#L60

Added line #L60 was not covered by tests

const onSessionEnd = useCallback(async (): Promise<void> => {
await endSession();
await endSession({ id: sessionId });

Check warning on line 63 in frontend/src/components/BrowserSession.tsx

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/BrowserSession.tsx#L63

Added line #L63 was not covered by tests
if (isCurrent) {
currentBrowserSessionId({
requestPolicy: "network-only",
});
currentUserId({
requestPolicy: "network-only",
});
window.location.reload();

Check warning on line 65 in frontend/src/components/BrowserSession.tsx

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/BrowserSession.tsx#L65

Added line #L65 was not covered by tests
}
}, [isCurrent, endSession, currentBrowserSessionId, currentUserId]);
}, [isCurrent, endSession, sessionId]);

Check warning on line 67 in frontend/src/components/BrowserSession.tsx

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/BrowserSession.tsx#L67

Added line #L67 was not covered by tests

return onSessionEnd;
};
Expand Down
72 changes: 17 additions & 55 deletions frontend/src/components/BrowserSessionList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.

import { atom, useAtom, useAtomValue, useSetAtom } from "jotai";
import { atomFamily } from "jotai/utils";
import { atomWithQuery } from "jotai-urql";
import { useTransition } from "react";
import { useState, useTransition } from "react";
import { useQuery } from "urql";

import { mapQueryAtom } from "../atoms";
import { graphql } from "../gql";
import { SessionState, PageInfo } from "../gql/graphql";
import {
atomForCurrentPagination,
atomWithPagination,
FIRST_PAGE,
Pagination,
} from "../pagination";
import { isOk, unwrap, unwrapOk } from "../result";
import { SessionState } from "../gql/graphql";
import { FIRST_PAGE, Pagination, usePages, usePagination } from "../pagination";

import BlockList from "./BlockList";
import BrowserSession from "./BrowserSession";
Expand Down Expand Up @@ -72,52 +63,22 @@
}
`);

const filterAtom = atom<SessionState | null>(SessionState.Active);
const currentPaginationAtom = atomForCurrentPagination();

const browserSessionListFamily = atomFamily((userId: string) => {
const browserSessionListQuery = atomWithQuery({
query: QUERY,
getVariables: (get) => ({
userId,
state: get(filterAtom),
...get(currentPaginationAtom),
}),
});

const browserSessionList = mapQueryAtom(
browserSessionListQuery,
(data) => data.user?.browserSessions || null,
const BrowserSessionList: React.FC<{ userId: string }> = ({ userId }) => {
const [pagination, setPagination] = usePagination();
const [pending, startTransition] = useTransition();
const [filter, setFilter] = useState<SessionState | null>(
SessionState.Active,

Check warning on line 70 in frontend/src/components/BrowserSessionList.tsx

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/BrowserSessionList.tsx#L67-L70

Added lines #L67 - L70 were not covered by tests
);

return browserSessionList;
});

const pageInfoFamily = atomFamily((userId: string) => {
const pageInfoAtom = atom(async (get): Promise<PageInfo | null> => {
const result = await get(browserSessionListFamily(userId));
return (isOk(result) && unwrapOk(result)?.pageInfo) || null;
const [result] = useQuery({
query: QUERY,
variables: { userId, state: filter, ...pagination },

Check warning on line 74 in frontend/src/components/BrowserSessionList.tsx

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/BrowserSessionList.tsx#L72-L74

Added lines #L72 - L74 were not covered by tests
});
return pageInfoAtom;
});

const paginationFamily = atomFamily((userId: string) => {
const paginationAtom = atomWithPagination(
currentPaginationAtom,
pageInfoFamily(userId),
);
if (result.error) throw result.error;
const browserSessions = result.data?.user?.browserSessions;
if (!browserSessions) throw new Error(); // Suspense mode is enabled

Check warning on line 78 in frontend/src/components/BrowserSessionList.tsx

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/BrowserSessionList.tsx#L76-L78

Added lines #L76 - L78 were not covered by tests

return paginationAtom;
});

const BrowserSessionList: React.FC<{ userId: string }> = ({ userId }) => {
const [pending, startTransition] = useTransition();
const result = useAtomValue(browserSessionListFamily(userId));
const setPagination = useSetAtom(currentPaginationAtom);
const [prevPage, nextPage] = useAtomValue(paginationFamily(userId));
const [filter, setFilter] = useAtom(filterAtom);
const [prevPage, nextPage] = usePages(pagination, browserSessions.pageInfo);

Check warning on line 80 in frontend/src/components/BrowserSessionList.tsx

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/BrowserSessionList.tsx#L80

Added line #L80 was not covered by tests

const browserSessions = unwrap(result);
if (browserSessions === null) return <>Failed to load browser sessions</>;

const paginate = (pagination: Pagination): void => {
Expand Down Expand Up @@ -145,6 +106,7 @@
<label>
<input
type="checkbox"
disabled={pending}

Check warning on line 109 in frontend/src/components/BrowserSessionList.tsx

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/BrowserSessionList.tsx#L109

Added line #L109 was not covered by tests
checked={filter === SessionState.Active}
onChange={toggleFilter}
/>{" "}
Expand Down
22 changes: 16 additions & 6 deletions frontend/src/components/CompatSession.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
// @vitest-environment happy-dom

import { create } from "react-test-renderer";
import { Provider } from "urql";
import { describe, expect, it, beforeAll } from "vitest";
import { never } from "wonka";

import { makeFragmentData } from "../gql";
import { WithLocation } from "../test-utils/WithLocation";
Expand All @@ -24,6 +26,10 @@ import { mockLocale } from "../test-utils/mockLocale";
import CompatSession, { FRAGMENT } from "./CompatSession";

describe("<CompatSession />", () => {
const mockClient = {
executeQuery: (): typeof never => never,
};

const baseSession = {
id: "session-id",
deviceId: "abcd1234",
Expand All @@ -42,9 +48,11 @@ describe("<CompatSession />", () => {
it("renders an active session", () => {
const session = makeFragmentData(baseSession, FRAGMENT);
const component = create(
<WithLocation>
<CompatSession session={session} />
</WithLocation>,
<Provider value={mockClient}>
<WithLocation>
<CompatSession session={session} />
</WithLocation>
</Provider>,
);
expect(component.toJSON()).toMatchSnapshot();
});
Expand All @@ -58,9 +66,11 @@ describe("<CompatSession />", () => {
FRAGMENT,
);
const component = create(
<WithLocation>
<CompatSession session={session} />
</WithLocation>,
<Provider value={mockClient}>
<WithLocation>
<CompatSession session={session} />
</WithLocation>
</Provider>,
);
expect(component.toJSON()).toMatchSnapshot();
});
Expand Down
Loading
Loading