mirror of
https://github.com/roleypoly/roleypoly.git
synced 2025-06-15 09:09:10 +00:00
chore: update prettier tab width for consistency (#175)
This commit is contained in:
parent
a931f8c69c
commit
f24d2fcc99
247 changed files with 7224 additions and 7375 deletions
|
@ -4,21 +4,18 @@ const { getLoader, loaderByName } = require('@craco/craco');
|
|||
const includePaths = [path.join(__dirname, '..')];
|
||||
|
||||
module.exports = {
|
||||
webpack: {
|
||||
alias: {},
|
||||
plugins: [],
|
||||
configure: (webpackConfig, { env, paths }) => {
|
||||
const { isFound, match } = getLoader(
|
||||
webpackConfig,
|
||||
loaderByName('babel-loader')
|
||||
);
|
||||
if (isFound) {
|
||||
const include = Array.isArray(match.loader.include)
|
||||
? match.loader.include
|
||||
: [match.loader.include];
|
||||
match.loader.include = [...include, ...includePaths];
|
||||
}
|
||||
return webpackConfig;
|
||||
},
|
||||
webpack: {
|
||||
alias: {},
|
||||
plugins: [],
|
||||
configure: (webpackConfig, { env, paths }) => {
|
||||
const { isFound, match } = getLoader(webpackConfig, loaderByName('babel-loader'));
|
||||
if (isFound) {
|
||||
const include = Array.isArray(match.loader.include)
|
||||
? match.loader.include
|
||||
: [match.loader.include];
|
||||
match.loader.include = [...include, ...includePaths];
|
||||
}
|
||||
return webpackConfig;
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
|
@ -1,56 +1,56 @@
|
|||
{
|
||||
"name": "@roleypoly/web",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "cross-env BUILD_PATH=../../dist craco build",
|
||||
"start": "cross-env PORT=6601 craco start",
|
||||
"test": "craco test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@reach/router": "^1.3.4",
|
||||
"@roleypoly/design-system": "*",
|
||||
"@roleypoly/misc-utils": "*",
|
||||
"@roleypoly/types": "*",
|
||||
"@testing-library/jest-dom": "^5.11.9",
|
||||
"@testing-library/react": "^11.2.5",
|
||||
"@testing-library/user-event": "^12.8.3",
|
||||
"@types/jest": "^26.0.20",
|
||||
"@types/node": "^14.14.34",
|
||||
"@types/react": "^17.0.3",
|
||||
"@types/react-dom": "^17.0.2",
|
||||
"memoize-one": "^5.1.1",
|
||||
"react": "^17.0.1",
|
||||
"react-dom": "^17.0.1",
|
||||
"react-helmet": "^6.1.0",
|
||||
"react-scripts": "4.0.3",
|
||||
"typescript": "^4.2.3",
|
||||
"web-vitals": "^1.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@craco/craco": "^6.1.1",
|
||||
"@types/react-helmet": "^6.1.0",
|
||||
"babel-loader": "8.1.0",
|
||||
"cross-env": "7.0.3",
|
||||
"ts-loader": "^8.0.18",
|
||||
"webpack": "4.44.2"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
}
|
||||
"name": "@roleypoly/web",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "cross-env BUILD_PATH=../../dist craco build",
|
||||
"start": "cross-env PORT=6601 craco start",
|
||||
"test": "craco test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@reach/router": "^1.3.4",
|
||||
"@roleypoly/design-system": "*",
|
||||
"@roleypoly/misc-utils": "*",
|
||||
"@roleypoly/types": "*",
|
||||
"@testing-library/jest-dom": "^5.11.9",
|
||||
"@testing-library/react": "^11.2.5",
|
||||
"@testing-library/user-event": "^12.8.3",
|
||||
"@types/jest": "^26.0.20",
|
||||
"@types/node": "^14.14.34",
|
||||
"@types/react": "^17.0.3",
|
||||
"@types/react-dom": "^17.0.2",
|
||||
"memoize-one": "^5.1.1",
|
||||
"react": "^17.0.1",
|
||||
"react-dom": "^17.0.1",
|
||||
"react-helmet": "^6.1.0",
|
||||
"react-scripts": "4.0.3",
|
||||
"typescript": "^4.2.3",
|
||||
"web-vitals": "^1.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@craco/craco": "^6.1.1",
|
||||
"@types/react-helmet": "^6.1.0",
|
||||
"babel-loader": "8.1.0",
|
||||
"cross-env": "7.0.3",
|
||||
"ts-loader": "^8.0.18",
|
||||
"webpack": "4.44.2"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,25 +1,25 @@
|
|||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
},
|
||||
{
|
||||
"src": "logo192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
},
|
||||
{
|
||||
"src": "logo512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#453e3d"
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
},
|
||||
{
|
||||
"src": "logo192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
},
|
||||
{
|
||||
"src": "logo512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#453e3d"
|
||||
}
|
||||
|
|
|
@ -12,30 +12,27 @@ 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>>;
|
||||
path?: string;
|
||||
default?: boolean;
|
||||
component: React.LazyExoticComponent<React.ComponentType<any>>;
|
||||
path?: string;
|
||||
default?: boolean;
|
||||
}) => (
|
||||
<React.Suspense fallback={<div>Loading...</div>}>
|
||||
<props.component {...props} />
|
||||
</React.Suspense>
|
||||
<React.Suspense fallback={<div>Loading...</div>}>
|
||||
<props.component {...props} />
|
||||
</React.Suspense>
|
||||
);
|
||||
|
||||
export const AppRouter = () => {
|
||||
return (
|
||||
<Router>
|
||||
<RouteWrapper component={LandingPage} path="/" />
|
||||
<RouteWrapper component={ServersPage} path="/servers" />
|
||||
<RouteWrapper component={PickerPage} path="/s/:serverID" />
|
||||
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={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>
|
||||
);
|
||||
<RouteWrapper component={DevToolsSetApi} path="/x/dev-tools/set-api" />
|
||||
<RouteWrapper component={DevToolsSessionDebug} path="/x/dev-tools/session-debug" />
|
||||
</Router>
|
||||
);
|
||||
};
|
||||
|
|
|
@ -3,63 +3,63 @@ import * as React from 'react';
|
|||
import { ApiContextProvider, useApiContext } from './ApiContext';
|
||||
|
||||
const fetchMock = (global.fetch = jest
|
||||
.fn()
|
||||
.mockImplementation(() => ({ json: async () => ({}) })));
|
||||
.fn()
|
||||
.mockImplementation(() => ({ json: async () => ({}) })));
|
||||
|
||||
const TestComponent = () => {
|
||||
const context = useApiContext();
|
||||
const context = useApiContext();
|
||||
|
||||
React.useEffect(() => {
|
||||
void context.fetch('/not-a-route');
|
||||
});
|
||||
React.useEffect(() => {
|
||||
void context.fetch('/not-a-route');
|
||||
});
|
||||
|
||||
return <>{context.apiUrl}</>;
|
||||
return <>{context.apiUrl}</>;
|
||||
};
|
||||
|
||||
const WrappedTestComponent = () => (
|
||||
<ApiContextProvider>
|
||||
<TestComponent />
|
||||
</ApiContextProvider>
|
||||
<ApiContextProvider>
|
||||
<TestComponent />
|
||||
</ApiContextProvider>
|
||||
);
|
||||
|
||||
it('correctly does fetch url requests', () => {
|
||||
render(<WrappedTestComponent />);
|
||||
render(<WrappedTestComponent />);
|
||||
|
||||
expect(fetchMock).toBeCalledWith('http://localhost:6609/not-a-route');
|
||||
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 />);
|
||||
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'
|
||||
);
|
||||
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'],
|
||||
['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;
|
||||
// @ts-ignore
|
||||
delete window.location;
|
||||
window.location = new URL(inputUrl) as any;
|
||||
|
||||
render(<WrappedTestComponent />);
|
||||
render(<WrappedTestComponent />);
|
||||
|
||||
expect(fetchMock).toBeCalledWith(`${outputUrl}/not-a-route`);
|
||||
expect(screen.getByText(outputUrl).innerHTML).toStrictEqual(outputUrl);
|
||||
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;
|
||||
localStorage.clear();
|
||||
fetchMock.mockClear();
|
||||
window.location = originalWindowLocation;
|
||||
});
|
||||
|
|
|
@ -2,46 +2,44 @@ import * as React from 'react';
|
|||
import { getDefaultApiUrl } from './getDefaultApiUrl';
|
||||
|
||||
type ApiContextData = {
|
||||
apiUrl: string;
|
||||
setApiUrl: (url: string) => void;
|
||||
fetch: (path: string, ...rest: any) => Promise<Response>;
|
||||
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();
|
||||
},
|
||||
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 [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);
|
||||
},
|
||||
};
|
||||
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(() => {
|
||||
const storedApiUrl = localStorage.getItem('api_url');
|
||||
if (storedApiUrl) {
|
||||
setApiUrl(storedApiUrl);
|
||||
}
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
localStorage.setItem('api_url', apiUrl);
|
||||
}, [apiUrl]);
|
||||
React.useEffect(() => {
|
||||
localStorage.setItem('api_url', apiUrl);
|
||||
}, [apiUrl]);
|
||||
|
||||
return (
|
||||
<ApiContext.Provider value={apiContextData}>{props.children}</ApiContext.Provider>
|
||||
);
|
||||
return (
|
||||
<ApiContext.Provider value={apiContextData}>{props.children}</ApiContext.Provider>
|
||||
);
|
||||
};
|
||||
|
|
|
@ -1,15 +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'],
|
||||
['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;
|
||||
const urlHostname = new URL(inputUrl).hostname;
|
||||
|
||||
expect(getDefaultApiUrl(urlHostname)).toStrictEqual(outputUrl);
|
||||
expect(getDefaultApiUrl(urlHostname)).toStrictEqual(outputUrl);
|
||||
});
|
||||
|
|
|
@ -1,16 +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';
|
||||
}
|
||||
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';
|
||||
}
|
||||
});
|
||||
|
|
|
@ -4,38 +4,38 @@ 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: [];
|
||||
};
|
||||
| {
|
||||
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: [],
|
||||
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 { session } = useSessionContext();
|
||||
const { recentGuilds } = useRecentGuilds();
|
||||
|
||||
const appShellProps: AppShellPropsT = {
|
||||
user: session?.user,
|
||||
guilds: session?.guilds,
|
||||
recentGuilds,
|
||||
};
|
||||
const appShellProps: AppShellPropsT = {
|
||||
user: session?.user,
|
||||
guilds: session?.guilds,
|
||||
recentGuilds,
|
||||
};
|
||||
|
||||
return (
|
||||
<AppShellPropsContext.Provider value={appShellProps}>
|
||||
{props.children}
|
||||
</AppShellPropsContext.Provider>
|
||||
);
|
||||
return (
|
||||
<AppShellPropsContext.Provider value={appShellProps}>
|
||||
{props.children}
|
||||
</AppShellPropsContext.Provider>
|
||||
);
|
||||
};
|
||||
|
|
|
@ -1,59 +1,59 @@
|
|||
import * as React from 'react';
|
||||
|
||||
type RecentGuildsT = {
|
||||
recentGuilds: string[];
|
||||
pushRecentGuild: (id: string) => void;
|
||||
recentGuilds: string[];
|
||||
pushRecentGuild: (id: string) => void;
|
||||
};
|
||||
|
||||
export const RecentGuilds = React.createContext<RecentGuildsT>({
|
||||
recentGuilds: [],
|
||||
pushRecentGuild: () => {},
|
||||
recentGuilds: [],
|
||||
pushRecentGuild: () => {},
|
||||
});
|
||||
|
||||
export const useRecentGuilds = () => React.useContext(RecentGuilds);
|
||||
|
||||
const saveState = (state: string[]) => {
|
||||
localStorage.setItem('rp_recent_guilds', JSON.stringify(state));
|
||||
localStorage.setItem('rp_recent_guilds', JSON.stringify(state));
|
||||
};
|
||||
|
||||
const pullState = (): string[] => {
|
||||
const rawState = localStorage.getItem('rp_recent_guilds');
|
||||
if (!rawState) {
|
||||
return [];
|
||||
}
|
||||
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 [];
|
||||
}
|
||||
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 [recentGuilds, setRecentGuilds] = React.useState<string[]>(pullState());
|
||||
|
||||
const recentGuildsData: RecentGuildsT = {
|
||||
recentGuilds,
|
||||
pushRecentGuild: (id: string) => {
|
||||
const nextState = [
|
||||
id,
|
||||
...recentGuilds.slice(0, 19).filter((guild) => guild !== id),
|
||||
];
|
||||
const recentGuildsData: RecentGuildsT = {
|
||||
recentGuilds,
|
||||
pushRecentGuild: (id: string) => {
|
||||
const nextState = [
|
||||
id,
|
||||
...recentGuilds.slice(0, 19).filter((guild) => guild !== id),
|
||||
];
|
||||
|
||||
if (recentGuilds[0] !== id) {
|
||||
setRecentGuilds(nextState);
|
||||
}
|
||||
},
|
||||
};
|
||||
if (recentGuilds[0] !== id) {
|
||||
setRecentGuilds(nextState);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
saveState(recentGuilds);
|
||||
}, [recentGuilds]);
|
||||
React.useEffect(() => {
|
||||
saveState(recentGuilds);
|
||||
}, [recentGuilds]);
|
||||
|
||||
return (
|
||||
<RecentGuilds.Provider value={recentGuildsData}>
|
||||
{props.children}
|
||||
</RecentGuilds.Provider>
|
||||
);
|
||||
return (
|
||||
<RecentGuilds.Provider value={recentGuildsData}>
|
||||
{props.children}
|
||||
</RecentGuilds.Provider>
|
||||
);
|
||||
};
|
||||
|
|
|
@ -3,114 +3,110 @@ 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;
|
||||
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();
|
||||
},
|
||||
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 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]
|
||||
);
|
||||
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.
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
// 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 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;
|
||||
}
|
||||
|
||||
// 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 || ''
|
||||
);
|
||||
}
|
||||
const serverSession: SessionContextT['session'] = await response.json();
|
||||
|
||||
// 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;
|
||||
}
|
||||
setSession(serverSession);
|
||||
sessionStorage.setItem('rp_session_data', JSON.stringify(serverSession));
|
||||
};
|
||||
|
||||
const serverSession: SessionContextT['session'] = await response.json();
|
||||
syncSession();
|
||||
}
|
||||
}, [
|
||||
sessionContextValue.session?.user,
|
||||
sessionContextValue.session?.sessionID,
|
||||
sessionContextValue,
|
||||
]);
|
||||
|
||||
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>
|
||||
);
|
||||
return (
|
||||
<SessionContext.Provider value={sessionContextValue}>
|
||||
{props.children}
|
||||
</SessionContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
const clearSessionData = () => {
|
||||
sessionStorage.removeItem('rp_session_data');
|
||||
localStorage.removeItem('rp_session_key');
|
||||
sessionStorage.removeItem('rp_session_data');
|
||||
localStorage.removeItem('rp_session_key');
|
||||
};
|
||||
|
|
|
@ -7,27 +7,27 @@ import { RecentGuildsProvider } from './contexts/recent-guilds/RecentGuildsConte
|
|||
import { SessionContextProvider } from './contexts/session/SessionContext';
|
||||
|
||||
const ProviderProvider = (props: {
|
||||
providerChain: typeof ApiContextProvider[];
|
||||
children: React.ReactNode;
|
||||
providerChain: typeof ApiContextProvider[];
|
||||
children: React.ReactNode;
|
||||
}) => {
|
||||
return props.providerChain.reduceRight(
|
||||
(acc, Provider) => <Provider>{acc}</Provider>,
|
||||
<>{props.children}</>
|
||||
);
|
||||
return props.providerChain.reduceRight(
|
||||
(acc, Provider) => <Provider>{acc}</Provider>,
|
||||
<>{props.children}</>
|
||||
);
|
||||
};
|
||||
|
||||
ReactDOM.render(
|
||||
<React.StrictMode>
|
||||
<ProviderProvider
|
||||
providerChain={[
|
||||
ApiContextProvider,
|
||||
SessionContextProvider,
|
||||
RecentGuildsProvider,
|
||||
AppShellPropsProvider,
|
||||
]}
|
||||
>
|
||||
<AppRouter />
|
||||
</ProviderProvider>
|
||||
</React.StrictMode>,
|
||||
document.getElementById('root')
|
||||
<React.StrictMode>
|
||||
<ProviderProvider
|
||||
providerChain={[
|
||||
ApiContextProvider,
|
||||
SessionContextProvider,
|
||||
RecentGuildsProvider,
|
||||
AppShellPropsProvider,
|
||||
]}
|
||||
>
|
||||
<AppRouter />
|
||||
</ProviderProvider>
|
||||
</React.StrictMode>,
|
||||
document.getElementById('root')
|
||||
);
|
||||
|
|
|
@ -5,50 +5,50 @@ import { useApiContext } from '../../contexts/api/ApiContext';
|
|||
import { Title } from '../../utils/metaTitle';
|
||||
|
||||
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);
|
||||
const [oauthLink, setOauthLink] = React.useState(`${apiUrl}/login-bounce`);
|
||||
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);
|
||||
const [oauthLink, setOauthLink] = React.useState(`${apiUrl}/login-bounce`);
|
||||
|
||||
React.useEffect(() => {
|
||||
const url = new URL(window.location.href);
|
||||
const callbackHost = new URL('/', url);
|
||||
const redirectServerID = url.searchParams.get('r');
|
||||
const redirectUrl = `${apiUrl}/login-bounce?cbh=${callbackHost.href}`;
|
||||
if (!redirectServerID) {
|
||||
window.location.href = redirectUrl;
|
||||
return;
|
||||
}
|
||||
|
||||
setOauthLink(redirectUrl);
|
||||
localStorage.setItem('rp_postauth_redirect', `/s/${redirectServerID}`);
|
||||
|
||||
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>;
|
||||
React.useEffect(() => {
|
||||
const url = new URL(window.location.href);
|
||||
const callbackHost = new URL('/', url);
|
||||
const redirectServerID = url.searchParams.get('r');
|
||||
const redirectUrl = `${apiUrl}/login-bounce?cbh=${callbackHost.href}`;
|
||||
if (!redirectServerID) {
|
||||
window.location.href = redirectUrl;
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Title title={'Login to Roleypoly'} />
|
||||
<AuthLogin
|
||||
guildSlug={guildSlug}
|
||||
onSendSecretCode={() => {}}
|
||||
discordOAuthLink={oauthLink}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
setOauthLink(redirectUrl);
|
||||
localStorage.setItem('rp_postauth_redirect', `/s/${redirectServerID}`);
|
||||
|
||||
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 (
|
||||
<>
|
||||
<Title title={'Login to Roleypoly'} />
|
||||
<AuthLogin
|
||||
guildSlug={guildSlug}
|
||||
onSendSecretCode={() => {}}
|
||||
discordOAuthLink={oauthLink}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
|
|
|
@ -2,23 +2,23 @@ import { useApiContext } from '../../contexts/api/ApiContext';
|
|||
import { useSessionContext } from '../../contexts/session/SessionContext';
|
||||
|
||||
const SessionDebug = () => {
|
||||
const session = useSessionContext();
|
||||
const api = useApiContext();
|
||||
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>
|
||||
);
|
||||
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;
|
||||
|
|
|
@ -3,49 +3,49 @@ import * as React from 'react';
|
|||
import { useApiContext } from '../../contexts/api/ApiContext';
|
||||
|
||||
const SetApi = () => {
|
||||
const apiContext = useApiContext();
|
||||
const [apiField, setApiField] = React.useState(apiContext.apiUrl);
|
||||
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();
|
||||
const setApi = () => {
|
||||
// Clear storage to get rid of old API data
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
|
||||
apiContext.setApiUrl(apiField);
|
||||
apiContext.setApiUrl(apiField);
|
||||
|
||||
navigate('/');
|
||||
};
|
||||
navigate('/');
|
||||
};
|
||||
|
||||
const quickSettingClick = (url: string) => () => {
|
||||
setApiField(url);
|
||||
};
|
||||
const quickSettingClick = (url: string) => () => {
|
||||
setApiField(url);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>
|
||||
<input
|
||||
type="text"
|
||||
value={apiField}
|
||||
onChange={(ev) => {
|
||||
setApiField(ev.target.value);
|
||||
}}
|
||||
/>
|
||||
<button onClick={setApi}>Set & 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>
|
||||
);
|
||||
return (
|
||||
<div>
|
||||
<div>
|
||||
<input
|
||||
type="text"
|
||||
value={apiField}
|
||||
onChange={(ev) => {
|
||||
setApiField(ev.target.value);
|
||||
}}
|
||||
/>
|
||||
<button onClick={setApi}>Set & 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;
|
||||
|
|
|
@ -6,19 +6,19 @@ import { useSessionContext } from '../contexts/session/SessionContext';
|
|||
import { Title } from '../utils/metaTitle';
|
||||
|
||||
const Landing = () => {
|
||||
const { isAuthenticated } = useSessionContext();
|
||||
const appShellProps = useAppShellProps();
|
||||
const { isAuthenticated } = useSessionContext();
|
||||
const appShellProps = useAppShellProps();
|
||||
|
||||
if (isAuthenticated) {
|
||||
return <Redirect to="/servers" />;
|
||||
}
|
||||
if (isAuthenticated) {
|
||||
return <Redirect to="/servers" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Title title={`Roleypoly - Tame your Discord roles.`} />
|
||||
<LandingTemplate {...appShellProps} />
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Title title={`Roleypoly - Tame your Discord roles.`} />
|
||||
<LandingTemplate {...appShellProps} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Landing;
|
||||
|
|
|
@ -2,23 +2,23 @@ import * as React from 'react';
|
|||
import { Title } from '../../utils/metaTitle';
|
||||
|
||||
const NewSession = () => {
|
||||
React.useEffect(() => {
|
||||
const url = new URL(window.location.href);
|
||||
const id = url.searchParams.get('session_id');
|
||||
if (id) {
|
||||
localStorage.setItem('rp_session_key', id);
|
||||
React.useEffect(() => {
|
||||
const url = new URL(window.location.href);
|
||||
const id = url.searchParams.get('session_id');
|
||||
if (id) {
|
||||
localStorage.setItem('rp_session_key', id);
|
||||
|
||||
const redirectUrl = localStorage.getItem('rp_postauth_redirect');
|
||||
window.location.href = redirectUrl || '/';
|
||||
}
|
||||
});
|
||||
const redirectUrl = localStorage.getItem('rp_postauth_redirect');
|
||||
window.location.href = redirectUrl || '/';
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<Title title="Logging you into Roleypoly..." />
|
||||
<div>Redirecting you...</div>
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Title title="Logging you into Roleypoly..." />
|
||||
<div>Redirecting you...</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default NewSession;
|
||||
|
|
|
@ -10,106 +10,106 @@ import { Title } from '../utils/metaTitle';
|
|||
import { makeRoleTransactions } from '../utils/roleTransactions';
|
||||
|
||||
type PickerProps = {
|
||||
serverID: string;
|
||||
serverID: string;
|
||||
};
|
||||
|
||||
const Picker = (props: PickerProps) => {
|
||||
const { session, authedFetch, isAuthenticated } = useSessionContext();
|
||||
const { pushRecentGuild } = useRecentGuilds();
|
||||
const appShellProps = useAppShellProps();
|
||||
const { session, authedFetch, isAuthenticated } = useSessionContext();
|
||||
const { pushRecentGuild } = useRecentGuilds();
|
||||
const appShellProps = useAppShellProps();
|
||||
|
||||
const [pickerData, setPickerData] = React.useState<PresentableGuild | null | false>(
|
||||
null
|
||||
);
|
||||
const [pending, setPending] = React.useState(false);
|
||||
const [pickerData, setPickerData] = React.useState<PresentableGuild | null | false>(
|
||||
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();
|
||||
React.useEffect(() => {
|
||||
const fetchPickerData = async () => {
|
||||
const response = await authedFetch(`/get-picker-data/${props.serverID}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (response.status !== 200) {
|
||||
setPickerData(false);
|
||||
return;
|
||||
}
|
||||
if (response.status !== 200) {
|
||||
setPickerData(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setPickerData(data);
|
||||
};
|
||||
|
||||
fetchPickerData();
|
||||
}, [props.serverID, authedFetch, pushRecentGuild]);
|
||||
|
||||
React.useCallback((serverID) => pushRecentGuild(serverID), [pushRecentGuild])(
|
||||
props.serverID
|
||||
);
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <Redirect to={`/auth/login?r=${props.serverID}`} replace />;
|
||||
}
|
||||
|
||||
if (pickerData === null) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
if (pickerData === false) {
|
||||
if (session && session.user && session.guilds) {
|
||||
const guildSlug = session.guilds.find((guild) => guild.id === props.serverID);
|
||||
if (!guildSlug) {
|
||||
throw new Error('placeholder: guild not found in user slugs, 404');
|
||||
}
|
||||
|
||||
return (
|
||||
<ServerSetupTemplate
|
||||
activeGuildId={props.serverID}
|
||||
guildSlug={guildSlug}
|
||||
{...appShellProps}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
throw new Error('placeholder: session state is odd, 404');
|
||||
}
|
||||
|
||||
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);
|
||||
setPickerData(data);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Title title={`${pickerData.guild.name} - Roleypoly`} />
|
||||
<RolePickerTemplate
|
||||
activeGuildId={props.serverID}
|
||||
{...appShellProps}
|
||||
guild={pickerData.guild}
|
||||
guildData={pickerData.data}
|
||||
member={pickerData.member}
|
||||
roles={pickerData.roles}
|
||||
editable={pickerData.guild.permissionLevel > UserGuildPermissions.User}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
fetchPickerData();
|
||||
}, [props.serverID, authedFetch, pushRecentGuild]);
|
||||
|
||||
React.useCallback((serverID) => pushRecentGuild(serverID), [pushRecentGuild])(
|
||||
props.serverID
|
||||
);
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <Redirect to={`/auth/login?r=${props.serverID}`} replace />;
|
||||
}
|
||||
|
||||
if (pickerData === null) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
if (pickerData === false) {
|
||||
if (session && session.user && session.guilds) {
|
||||
const guildSlug = session.guilds.find((guild) => guild.id === props.serverID);
|
||||
if (!guildSlug) {
|
||||
throw new Error('placeholder: guild not found in user slugs, 404');
|
||||
}
|
||||
|
||||
return (
|
||||
<ServerSetupTemplate
|
||||
activeGuildId={props.serverID}
|
||||
guildSlug={guildSlug}
|
||||
{...appShellProps}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
throw new Error('placeholder: session state is odd, 404');
|
||||
}
|
||||
|
||||
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 (
|
||||
<>
|
||||
<Title title={`${pickerData.guild.name} - Roleypoly`} />
|
||||
<RolePickerTemplate
|
||||
activeGuildId={props.serverID}
|
||||
{...appShellProps}
|
||||
guild={pickerData.guild}
|
||||
guildData={pickerData.data}
|
||||
member={pickerData.member}
|
||||
roles={pickerData.roles}
|
||||
editable={pickerData.guild.permissionLevel > UserGuildPermissions.User}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Picker;
|
||||
|
|
|
@ -6,18 +6,18 @@ import { useSessionContext } from '../contexts/session/SessionContext';
|
|||
import { Title } from '../utils/metaTitle';
|
||||
|
||||
const ServersPage = () => {
|
||||
const { isAuthenticated, session } = useSessionContext();
|
||||
const appShellProps = useAppShellProps();
|
||||
if (!isAuthenticated || !session) {
|
||||
return <Redirect to="/" />;
|
||||
}
|
||||
const { isAuthenticated, session } = useSessionContext();
|
||||
const appShellProps = useAppShellProps();
|
||||
if (!isAuthenticated || !session) {
|
||||
return <Redirect to="/" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Title title={'Your Guilds - Roleypoly'} />
|
||||
<ServersTemplate {...appShellProps} />
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Title title={'Your Guilds - Roleypoly'} />
|
||||
<ServersTemplate {...appShellProps} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ServersPage;
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import Head from 'react-helmet';
|
||||
|
||||
export const Title = (props: { title: string }) => (
|
||||
<Head>
|
||||
<title>{props.title}</title>
|
||||
</Head>
|
||||
<Head>
|
||||
<title>{props.title}</title>
|
||||
</Head>
|
||||
);
|
||||
|
|
|
@ -2,24 +2,24 @@ 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 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,
|
||||
},
|
||||
])
|
||||
);
|
||||
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,
|
||||
},
|
||||
])
|
||||
);
|
||||
});
|
||||
|
|
|
@ -1,30 +1,30 @@
|
|||
import { Role, RoleTransaction, TransactionType } from '@roleypoly/types';
|
||||
|
||||
export const makeRoleTransactions = (
|
||||
oldRoles: Role['id'][],
|
||||
newRoles: Role['id'][]
|
||||
oldRoles: Role['id'][],
|
||||
newRoles: Role['id'][]
|
||||
): RoleTransaction[] => {
|
||||
const transactions: 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,
|
||||
});
|
||||
}
|
||||
// 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,
|
||||
});
|
||||
}
|
||||
// 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;
|
||||
return transactions;
|
||||
};
|
||||
|
|
|
@ -1,20 +1,20 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"]
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue