Reach parity with last web iteration. (#162)

* feat: add Api and Session contexts

* feat(web): add machinery/new-session

* feat(web): add servers page

* chore(web): AppRouter spacing/ordering

* feat(web): add picker, missing update-roles call for now

* feat(web): add picker saves

* chore: add roleTransactions tests

* feat(web): add auth/login
This commit is contained in:
41666 2021-03-13 04:42:07 -05:00 committed by GitHub
parent f65779f925
commit cd448b56c9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 567 additions and 7 deletions

View file

@ -32,7 +32,7 @@ export const Authed = (props: Props) => {
<MastheadBase>
<MastheadAlignment>
<MastheadLeft>
<MastheadA href="/servers">
<MastheadA to="/servers">
<DynamicLogomark height={35} />
</MastheadA>
<InteractionBase

View file

@ -14,12 +14,12 @@ export const Guest = () => (
<MastheadBase>
<MastheadAlignment>
<MastheadLeft>
<MastheadA href="/">
<MastheadA to="/">
<DynamicLogotype height={30} />
</MastheadA>
</MastheadLeft>
<MastheadRight>
<MastheadA href="/auth/login">
<MastheadA to="/auth/login">
<Button size="small">
Login{' '}
<FaSignInAlt

View file

@ -1,3 +1,4 @@
import { Link } from '@reach/router';
import { onSmallScreen } from '@roleypoly/design-system/atoms/breakpoints';
import { palette } from '@roleypoly/design-system/atoms/colors';
import { transitions } from '@roleypoly/design-system/atoms/timings';
@ -66,7 +67,7 @@ export const InteractionBase = styled.div<InteractionBaseProps>`
}
`;
export const MastheadA = styled.a`
export const MastheadA = styled(Link)`
display: flex;
align-items: center;
justify-content: center;

View 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;
});

View file

@ -0,0 +1,45 @@
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(),
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());
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>
);
};

View file

@ -0,0 +1,14 @@
import { getDefaultApiUrl } from './getDefaultApiUrl';
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'],
])('matches %s to %s', (inputUrl, outputUrl) => {
const urlHostname = new URL(inputUrl).hostname;
expect(getDefaultApiUrl(urlHostname)).toStrictEqual(outputUrl);
});

View file

@ -0,0 +1,11 @@
export const getDefaultApiUrl = (host: string = window.location.hostname) => {
if (/roleypoly.com$/.test(host)) {
return 'https://api-prod.roleypoly.com';
} else if (/roleypoly\.pages\.dev$/.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';
}
};

View file

@ -2,6 +2,14 @@ import { Router } from '@reach/router';
import * as React from 'react';
const LandingPage = React.lazy(() => import('../pages/landing'));
const ServersPage = React.lazy(() => import('../pages/servers'));
const PickerPage = React.lazy(() => import('../pages/picker'));
const AuthLogin = React.lazy(() => import('../pages/auth/login'));
const MachineryNewSession = React.lazy(() => import('../pages/machinery/new-session'));
const DevToolsSetApi = React.lazy(() => import('../pages/dev-tools/set-api'));
const DevToolsSessionDebug = React.lazy(() => import('../pages/dev-tools/session-debug'));
const RouteWrapper = (props: {
component: React.LazyExoticComponent<React.ComponentType<any>>;
@ -17,6 +25,17 @@ export const AppRouter = () => {
return (
<Router>
<RouteWrapper component={LandingPage} path="/" />
<RouteWrapper component={ServersPage} path="/servers" />
<RouteWrapper component={PickerPage} path="/s/:serverID" />
<RouteWrapper component={MachineryNewSession} path="/machinery/new-session" />
<RouteWrapper component={AuthLogin} path="/auth/login" />
<RouteWrapper component={DevToolsSetApi} path="/x/dev-tools/set-api" />
<RouteWrapper
component={DevToolsSessionDebug}
path="/x/dev-tools/session-debug"
/>
</Router>
);
};

View file

@ -1 +0,0 @@
export * from './AppRouter';

View file

@ -1,10 +1,16 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { AppRouter } from './app-router';
import { ApiContextProvider } from './api-context/ApiContext';
import { AppRouter } from './app-router/AppRouter';
import { SessionContextProvider } from './session-context/SessionContext';
ReactDOM.render(
<React.StrictMode>
<AppRouter />
<ApiContextProvider>
<SessionContextProvider>
<AppRouter />
</SessionContextProvider>
</ApiContextProvider>
</React.StrictMode>,
document.getElementById('root')
);

View file

@ -0,0 +1,38 @@
import { AuthLogin } from '@roleypoly/design-system/templates/auth-login';
import { GuildSlug } from '@roleypoly/types';
import React from 'react';
import { useApiContext } from '../../api-context/ApiContext';
const Login = () => {
const { apiUrl, fetch } = useApiContext();
// If ?r is in query, then let's render the slug page
// If not, redirect.
const [guildSlug, setGuildSlug] = React.useState<GuildSlug | null>(null);
React.useEffect(() => {
const url = new URL(window.location.href);
const redirectServerID = url.searchParams.get('r');
if (!redirectServerID) {
window.location.href = `${apiUrl}/login-bounce`;
return;
}
const fetchGuildSlug = async (id: string) => {
const response = await fetch(`/get-slug/${id}`);
if (response.status === 200) {
const slug = await response.json();
setGuildSlug(slug);
}
};
fetchGuildSlug(redirectServerID);
}, [apiUrl, fetch]);
if (guildSlug === null) {
return <div>Loading...</div>;
}
return <AuthLogin guildSlug={guildSlug} onSendSecretCode={() => {}} />;
};
export default Login;

View file

@ -0,0 +1,24 @@
import { useApiContext } from '../../api-context/ApiContext';
import { useSessionContext } from '../../session-context/SessionContext';
const SessionDebug = () => {
const session = useSessionContext();
const api = useApiContext();
return (
<pre>
{JSON.stringify(
{
apiUrl: api.apiUrl,
isAuthenticated: session.isAuthenticated,
user: session.session?.user || null,
guilds: session.session?.guilds || null,
},
null,
' '
)}
</pre>
);
};
export default SessionDebug;

View file

@ -0,0 +1,51 @@
import { navigate } from '@reach/router';
import * as React from 'react';
import { useApiContext } from '../../api-context/ApiContext';
const SetApi = () => {
const apiContext = useApiContext();
const [apiField, setApiField] = React.useState(apiContext.apiUrl);
const setApi = () => {
// Clear storage to get rid of old API data
localStorage.clear();
sessionStorage.clear();
apiContext.setApiUrl(apiField);
navigate('/');
};
const quickSettingClick = (url: string) => () => {
setApiField(url);
};
return (
<div>
<div>
<input
type="text"
value={apiField}
onChange={(ev) => {
setApiField(ev.target.value);
}}
/>
<button onClick={setApi}>Set &amp; Go</button>
</div>
<div>
Quick Settings:
<button onClick={quickSettingClick('https://api-prod.roleypoly.com')}>
Production (api-prod)
</button>
<button onClick={quickSettingClick('https://api-stage.roleypoly.com')}>
Staging (api-stage)
</button>
<button onClick={quickSettingClick('http://localhost:6609')}>
Local (:6609)
</button>
</div>
</div>
);
};
export default SetApi;

View file

@ -1,7 +1,15 @@
import { Redirect } from '@reach/router';
import { LandingTemplate } from '@roleypoly/design-system/templates/landing';
import * as React from 'react';
import { useSessionContext } from '../session-context/SessionContext';
const Landing = () => {
const { isAuthenticated } = useSessionContext();
if (isAuthenticated) {
return <Redirect to="/servers" />;
}
return <LandingTemplate />;
};

View file

@ -0,0 +1,16 @@
import * as React from 'react';
const NewSession = () => {
React.useEffect(() => {
const url = new URL(window.location.href);
const id = url.searchParams.get('session_id');
if (id) {
window.location.href = '/';
localStorage.setItem('rp_session_key', id);
}
});
return <div>Redirecting you...</div>;
};
export default NewSession;

View file

@ -0,0 +1,77 @@
import { Redirect } from '@reach/router';
import { RolePickerTemplate } from '@roleypoly/design-system/templates/role-picker';
import { PresentableGuild, RoleUpdate, UserGuildPermissions } from '@roleypoly/types';
import * as React from 'react';
import { useSessionContext } from '../session-context/SessionContext';
import { makeRoleTransactions } from '../utils/roleTransactions';
type PickerProps = {
serverID: string;
};
const Picker = (props: PickerProps) => {
const { session, authedFetch, isAuthenticated } = useSessionContext();
const [pickerData, setPickerData] = React.useState<PresentableGuild | null>(null);
const [pending, setPending] = React.useState(false);
React.useEffect(() => {
const fetchPickerData = async () => {
const response = await authedFetch(`/get-picker-data/${props.serverID}`);
const data = await response.json();
setPickerData(data);
};
fetchPickerData();
}, [props.serverID, authedFetch]);
if (!isAuthenticated) {
return <Redirect to={`/auth/login?r=${props.serverID}`} replace />;
}
if (pickerData === null) {
return <div>Loading...</div>;
}
const onSubmit = async (submittedRoles: string[]) => {
if (pending === true) {
return;
}
setPending(true);
const updatePayload: RoleUpdate = {
knownState: pickerData.member.roles,
transactions: makeRoleTransactions(pickerData.member.roles, submittedRoles),
};
const response = await authedFetch(`/update-roles/${props.serverID}`, {
method: 'PATCH',
body: JSON.stringify(updatePayload),
});
if (response.status === 200) {
setPickerData({
...pickerData,
member: { ...pickerData.member, roles: (await response.json()).roles },
});
}
setPending(false);
};
return (
<RolePickerTemplate
activeGuildId={props.serverID}
user={session?.user}
guilds={session?.guilds || []}
guild={pickerData.guild}
guildData={pickerData.data}
member={pickerData.member}
roles={pickerData.roles}
editable={pickerData.guild.permissionLevel > UserGuildPermissions.User}
onSubmit={onSubmit}
/>
);
};
export default Picker;

View file

@ -0,0 +1,15 @@
import { Redirect } from '@reach/router';
import { ServersTemplate } from '@roleypoly/design-system/templates/servers';
import * as React from 'react';
import { useSessionContext } from '../session-context/SessionContext';
const ServersPage = () => {
const { isAuthenticated, session } = useSessionContext();
if (!isAuthenticated || !session) {
return <Redirect to="/" />;
}
return <ServersTemplate guilds={session.guilds || []} user={session.user} />;
};
export default ServersPage;

View file

@ -0,0 +1,116 @@
import { SessionData } from '@roleypoly/types';
import * as React from 'react';
import { useApiContext } from '../api-context/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');
};

View file

@ -0,0 +1,25 @@
import { RoleTransaction, TransactionType } from '@roleypoly/types';
import { makeRoleTransactions } from './roleTransactions';
it('creates a transactional diff of two sets of roles', () => {
const currentRoles = ['aaa', 'bbb', 'ccc', 'ddd'];
const nextRoles = ['bbb', 'ccc', 'ddd', 'eee', 'fff']; // removes aaa, adds eee + fff
const transactions = makeRoleTransactions(currentRoles, nextRoles);
expect(transactions).toEqual(
expect.arrayContaining<RoleTransaction>([
{
id: 'aaa',
action: TransactionType.Remove,
},
{
id: 'fff',
action: TransactionType.Add,
},
{
id: 'eee',
action: TransactionType.Add,
},
])
);
});

View file

@ -0,0 +1,30 @@
import { Role, RoleTransaction, TransactionType } from '@roleypoly/types';
export const makeRoleTransactions = (
oldRoles: Role['id'][],
newRoles: Role['id'][]
): RoleTransaction[] => {
const transactions: RoleTransaction[] = [];
// Removes: old roles not in new roles
for (let oldID of oldRoles) {
if (!newRoles.includes(oldID)) {
transactions.push({
id: oldID,
action: TransactionType.Remove,
});
}
}
// Adds: new roles not in old roles
for (let newID of newRoles) {
if (!oldRoles.includes(newID)) {
transactions.push({
id: newID,
action: TransactionType.Add,
});
}
}
return transactions;
};