mirror of
https://github.com/roleypoly/roleypoly.git
synced 2025-06-17 01:59:08 +00:00
* feat(web): add server-setup page for when bot isn't in the server picked * chore: move contexts into their own folder * feat(web): add recent guilds context, and app shell helper context * feat(web): show recent guilds in masthead * feat(web): functionally add recents to servers list * fix(web): correct styling for servers listing recents/all headers * fix(web): correct some type issues with appShellProps * fix(web): don't show ServerListing recents when recents is empty
This commit is contained in:
parent
3a36d7a85d
commit
99952aa19f
22 changed files with 302 additions and 66 deletions
65
packages/web/src/contexts/api/ApiContext.spec.tsx
Normal file
65
packages/web/src/contexts/api/ApiContext.spec.tsx
Normal file
|
@ -0,0 +1,65 @@
|
|||
import { render, screen } from '@testing-library/react';
|
||||
import * as React from 'react';
|
||||
import { ApiContextProvider, useApiContext } from './ApiContext';
|
||||
|
||||
const fetchMock = (global.fetch = jest
|
||||
.fn()
|
||||
.mockImplementation(() => ({ json: async () => ({}) })));
|
||||
|
||||
const TestComponent = () => {
|
||||
const context = useApiContext();
|
||||
|
||||
React.useEffect(() => {
|
||||
void context.fetch('/not-a-route');
|
||||
});
|
||||
|
||||
return <>{context.apiUrl}</>;
|
||||
};
|
||||
|
||||
const WrappedTestComponent = () => (
|
||||
<ApiContextProvider>
|
||||
<TestComponent />
|
||||
</ApiContextProvider>
|
||||
);
|
||||
|
||||
it('correctly does fetch url requests', () => {
|
||||
render(<WrappedTestComponent />);
|
||||
|
||||
expect(fetchMock).toBeCalledWith('http://localhost:6609/not-a-route');
|
||||
});
|
||||
|
||||
it('sets up api context when localStorage is set', () => {
|
||||
localStorage.setItem('api_url', 'https://abcde.roleypoly.test');
|
||||
render(<WrappedTestComponent />);
|
||||
|
||||
expect(fetchMock).toBeCalledWith('https://abcde.roleypoly.test/not-a-route');
|
||||
expect(screen.getByText('https://abcde.roleypoly.test').innerHTML).toStrictEqual(
|
||||
'https://abcde.roleypoly.test'
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['https://next.roleypoly.com/servers', 'https://api-prod.roleypoly.com'],
|
||||
['https://roleypoly.com/servers', 'https://api-prod.roleypoly.com'],
|
||||
['https://notroleypolybutclose.com/servers', 'https://api-prod.roleypoly.com'],
|
||||
['https://myhash.roleypoly.pages.dev/servers', 'https://api-stage.roleypoly.com'],
|
||||
['http://localhost:6601/servers', 'http://localhost:6609'],
|
||||
['http://127.0.0.1:6601/servers', 'http://localhost:6609'],
|
||||
])('sets up api context based on window.location.href = %s', (inputUrl, outputUrl) => {
|
||||
// @ts-ignore
|
||||
delete window.location;
|
||||
window.location = new URL(inputUrl) as any;
|
||||
|
||||
render(<WrappedTestComponent />);
|
||||
|
||||
expect(fetchMock).toBeCalledWith(`${outputUrl}/not-a-route`);
|
||||
expect(screen.getByText(outputUrl).innerHTML).toStrictEqual(outputUrl);
|
||||
});
|
||||
|
||||
const originalWindowLocation = window.location;
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
fetchMock.mockClear();
|
||||
window.location = originalWindowLocation;
|
||||
});
|
47
packages/web/src/contexts/api/ApiContext.tsx
Normal file
47
packages/web/src/contexts/api/ApiContext.tsx
Normal file
|
@ -0,0 +1,47 @@
|
|||
import * as React from 'react';
|
||||
import { getDefaultApiUrl } from './getDefaultApiUrl';
|
||||
|
||||
type ApiContextData = {
|
||||
apiUrl: string;
|
||||
setApiUrl: (url: string) => void;
|
||||
fetch: (path: string, ...rest: any) => Promise<Response>;
|
||||
};
|
||||
|
||||
export const ApiContext = React.createContext<ApiContextData>({
|
||||
apiUrl: getDefaultApiUrl(window.location.hostname),
|
||||
setApiUrl: () => {},
|
||||
fetch: async () => {
|
||||
return new Response();
|
||||
},
|
||||
});
|
||||
|
||||
export const useApiContext = () => React.useContext(ApiContext);
|
||||
|
||||
export const ApiContextProvider = (props: { children: React.ReactNode }) => {
|
||||
const [apiUrl, setApiUrl] = React.useState(
|
||||
getDefaultApiUrl(window.location.hostname)
|
||||
);
|
||||
|
||||
const apiContextData: ApiContextData = {
|
||||
apiUrl,
|
||||
setApiUrl,
|
||||
fetch: async (path: string, ...rest: any): Promise<Response> => {
|
||||
return fetch(`${apiUrl}${path}`, ...rest);
|
||||
},
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
const storedApiUrl = localStorage.getItem('api_url');
|
||||
if (storedApiUrl) {
|
||||
setApiUrl(storedApiUrl);
|
||||
}
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
localStorage.setItem('api_url', apiUrl);
|
||||
}, [apiUrl]);
|
||||
|
||||
return (
|
||||
<ApiContext.Provider value={apiContextData}>{props.children}</ApiContext.Provider>
|
||||
);
|
||||
};
|
15
packages/web/src/contexts/api/getDefaultApiUrl.spec.ts
Normal file
15
packages/web/src/contexts/api/getDefaultApiUrl.spec.ts
Normal file
|
@ -0,0 +1,15 @@
|
|||
import { getDefaultApiUrl } from './getDefaultApiUrl';
|
||||
|
||||
it.each([
|
||||
['https://next.roleypoly.com/servers', 'https://api-prod.roleypoly.com'],
|
||||
['https://stage.roleypoly.com/servers', 'https://api-stage.roleypoly.com'],
|
||||
['https://roleypoly.com/servers', 'https://api-prod.roleypoly.com'],
|
||||
['https://notroleypolybutclose.com/servers', 'https://api-prod.roleypoly.com'],
|
||||
['https://myhash.roleypoly.pages.dev/servers', 'https://api-stage.roleypoly.com'],
|
||||
['http://localhost:6601/servers', 'http://localhost:6609'],
|
||||
['http://127.0.0.1:6601/servers', 'http://localhost:6609'],
|
||||
])('matches %s to %s', (inputUrl, outputUrl) => {
|
||||
const urlHostname = new URL(inputUrl).hostname;
|
||||
|
||||
expect(getDefaultApiUrl(urlHostname)).toStrictEqual(outputUrl);
|
||||
});
|
16
packages/web/src/contexts/api/getDefaultApiUrl.ts
Normal file
16
packages/web/src/contexts/api/getDefaultApiUrl.ts
Normal file
|
@ -0,0 +1,16 @@
|
|||
import * as memoizeOne from 'memoize-one';
|
||||
|
||||
export const getDefaultApiUrl = memoizeOne.default((host: string) => {
|
||||
if (/^roleypoly\.com$/.test(host)) {
|
||||
return 'https://api-prod.roleypoly.com';
|
||||
} else if (
|
||||
/roleypoly\.pages\.dev$/.test(host) ||
|
||||
/^stage\.roleypoly\.com$/.test(host)
|
||||
) {
|
||||
return 'https://api-stage.roleypoly.com';
|
||||
} else if (/\blocalhost|127\.0\.0\.1\b/.test(host)) {
|
||||
return 'http://localhost:6609';
|
||||
} else {
|
||||
return 'https://api-prod.roleypoly.com';
|
||||
}
|
||||
});
|
41
packages/web/src/contexts/app-shell/AppShellContext.tsx
Normal file
41
packages/web/src/contexts/app-shell/AppShellContext.tsx
Normal file
|
@ -0,0 +1,41 @@
|
|||
import { AppShellProps } from '@roleypoly/design-system/organisms/app-shell';
|
||||
import * as React from 'react';
|
||||
import { useRecentGuilds } from '../recent-guilds/RecentGuildsContext';
|
||||
import { useSessionContext } from '../session/SessionContext';
|
||||
|
||||
type AppShellPropsT =
|
||||
| {
|
||||
user: Required<AppShellProps['user']>;
|
||||
guilds: Required<AppShellProps['guilds']>;
|
||||
recentGuilds: Required<AppShellProps['recentGuilds']>;
|
||||
}
|
||||
| {
|
||||
user: undefined;
|
||||
guilds: undefined;
|
||||
recentGuilds: [];
|
||||
};
|
||||
|
||||
export const AppShellPropsContext = React.createContext<AppShellPropsT>({
|
||||
user: undefined,
|
||||
guilds: undefined,
|
||||
recentGuilds: [],
|
||||
});
|
||||
|
||||
export const useAppShellProps = () => React.useContext(AppShellPropsContext);
|
||||
|
||||
export const AppShellPropsProvider = (props: { children: React.ReactNode }) => {
|
||||
const { session } = useSessionContext();
|
||||
const { recentGuilds } = useRecentGuilds();
|
||||
|
||||
const appShellProps: AppShellPropsT = {
|
||||
user: session?.user,
|
||||
guilds: session?.guilds,
|
||||
recentGuilds,
|
||||
};
|
||||
|
||||
return (
|
||||
<AppShellPropsContext.Provider value={appShellProps}>
|
||||
{props.children}
|
||||
</AppShellPropsContext.Provider>
|
||||
);
|
||||
};
|
|
@ -0,0 +1,59 @@
|
|||
import * as React from 'react';
|
||||
|
||||
type RecentGuildsT = {
|
||||
recentGuilds: string[];
|
||||
pushRecentGuild: (id: string) => void;
|
||||
};
|
||||
|
||||
export const RecentGuilds = React.createContext<RecentGuildsT>({
|
||||
recentGuilds: [],
|
||||
pushRecentGuild: () => {},
|
||||
});
|
||||
|
||||
export const useRecentGuilds = () => React.useContext(RecentGuilds);
|
||||
|
||||
const saveState = (state: string[]) => {
|
||||
localStorage.setItem('rp_recent_guilds', JSON.stringify(state));
|
||||
};
|
||||
|
||||
const pullState = (): string[] => {
|
||||
const rawState = localStorage.getItem('rp_recent_guilds');
|
||||
if (!rawState) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(rawState);
|
||||
} catch (e) {
|
||||
console.warn('RecentGuilds failed to re-hydrate saved state', e);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const RecentGuildsProvider = (props: { children: React.ReactNode }) => {
|
||||
const [recentGuilds, setRecentGuilds] = React.useState<string[]>(pullState());
|
||||
|
||||
const recentGuildsData: RecentGuildsT = {
|
||||
recentGuilds,
|
||||
pushRecentGuild: (id: string) => {
|
||||
const nextState = [
|
||||
id,
|
||||
...recentGuilds.slice(0, 19).filter((guild) => guild !== id),
|
||||
];
|
||||
|
||||
if (recentGuilds[0] !== id) {
|
||||
setRecentGuilds(nextState);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
saveState(recentGuilds);
|
||||
}, [recentGuilds]);
|
||||
|
||||
return (
|
||||
<RecentGuilds.Provider value={recentGuildsData}>
|
||||
{props.children}
|
||||
</RecentGuilds.Provider>
|
||||
);
|
||||
};
|
116
packages/web/src/contexts/session/SessionContext.tsx
Normal file
116
packages/web/src/contexts/session/SessionContext.tsx
Normal file
|
@ -0,0 +1,116 @@
|
|||
import { SessionData } from '@roleypoly/types';
|
||||
import * as React from 'react';
|
||||
import { useApiContext } from '../api/ApiContext';
|
||||
|
||||
type SessionContextT = {
|
||||
session?: Omit<Partial<SessionData>, 'tokens'>;
|
||||
setSession: (session?: SessionContextT['session']) => void;
|
||||
authedFetch: (url: string, opts?: RequestInit) => Promise<Response>;
|
||||
isAuthenticated: boolean;
|
||||
};
|
||||
|
||||
const SessionContext = React.createContext<SessionContextT>({
|
||||
isAuthenticated: false,
|
||||
setSession: () => {},
|
||||
authedFetch: async () => {
|
||||
return new Response();
|
||||
},
|
||||
});
|
||||
|
||||
export const useSessionContext = () => React.useContext(SessionContext);
|
||||
|
||||
export const SessionContextProvider = (props: { children: React.ReactNode }) => {
|
||||
const api = useApiContext();
|
||||
const [session, setSession] = React.useState<SessionContextT['session']>(undefined);
|
||||
|
||||
const sessionContextValue: SessionContextT = React.useMemo(
|
||||
() => ({
|
||||
session,
|
||||
setSession,
|
||||
authedFetch: (url: string, opts?: RequestInit) => {
|
||||
return api.fetch(url, {
|
||||
...opts,
|
||||
headers: {
|
||||
...opts?.headers,
|
||||
authorization: session?.sessionID
|
||||
? `Bearer ${session?.sessionID}`
|
||||
: undefined,
|
||||
},
|
||||
});
|
||||
},
|
||||
isAuthenticated: !!session && !!session.sessionID && !!session.user,
|
||||
}),
|
||||
[session, api]
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
// No session is set, do we have one available?
|
||||
if (!sessionContextValue.session || !sessionContextValue.session.sessionID) {
|
||||
// We may have the full state in session storage...
|
||||
const storedSessionData = sessionStorage.getItem('rp_session_data');
|
||||
if (storedSessionData) {
|
||||
try {
|
||||
setSession(JSON.parse(storedSessionData));
|
||||
return;
|
||||
} catch (e) {
|
||||
// Oops, this data is wrong.
|
||||
}
|
||||
}
|
||||
|
||||
// But if not, we have the key, maybe?
|
||||
const storedSessionID = localStorage.getItem('rp_session_key');
|
||||
if (storedSessionID && storedSessionID !== '') {
|
||||
setSession({ sessionID: storedSessionID });
|
||||
return;
|
||||
}
|
||||
|
||||
// If we hit here, we're definitely not authenticated.
|
||||
return;
|
||||
}
|
||||
|
||||
// If a session is set and it's not stored, set it now.
|
||||
if (
|
||||
localStorage.getItem('rp_session_key') !==
|
||||
sessionContextValue.session.sessionID
|
||||
) {
|
||||
localStorage.setItem(
|
||||
'rp_session_key',
|
||||
sessionContextValue.session.sessionID || ''
|
||||
);
|
||||
}
|
||||
|
||||
// Session is set, but we don't have data. Server sup?
|
||||
if (sessionContextValue.session.sessionID && !sessionContextValue.session.user) {
|
||||
const syncSession = async () => {
|
||||
const response = await sessionContextValue.authedFetch('/get-session');
|
||||
if (response.status !== 200) {
|
||||
console.error('get-session failed', { response });
|
||||
clearSessionData();
|
||||
return;
|
||||
}
|
||||
|
||||
const serverSession: SessionContextT['session'] = await response.json();
|
||||
|
||||
setSession(serverSession);
|
||||
sessionStorage.setItem('rp_session_data', JSON.stringify(serverSession));
|
||||
};
|
||||
|
||||
syncSession();
|
||||
}
|
||||
}, [
|
||||
sessionContextValue.session?.user,
|
||||
sessionContextValue.session?.sessionID,
|
||||
sessionContextValue,
|
||||
]);
|
||||
|
||||
return (
|
||||
<SessionContext.Provider value={sessionContextValue}>
|
||||
{props.children}
|
||||
</SessionContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
const clearSessionData = () => {
|
||||
sessionStorage.removeItem('rp_session_data');
|
||||
localStorage.removeItem('rp_session_key');
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue