remove unused setup flow

This commit is contained in:
Sidney Alcantara
2022-03-03 17:40:15 +11:00
parent 221eb933bd
commit 927cfa72df
14 changed files with 7 additions and 1319 deletions

View File

@@ -52,7 +52,7 @@ const UserSettingsPage = lazy(() => import("./pages/Settings/UserSettings" /* we
// prettier-ignore
const UserManagementPage = lazy(() => import("./pages/Settings/UserManagement" /* webpackChunkName: "UserManagementPage" */));
// prettier-ignore
const BasicSetupPage = lazy(() => import("@src/pages/Setup/RowyAppSetup" /* webpackChunkName: "BasicSetupPage" */));
const SetupPage = lazy(() => import("@src/pages/Setup" /* webpackChunkName: "SetupPage" */));
export default function App() {
return (
@@ -97,7 +97,7 @@ export default function App() {
<Route
exact
path={routes.setup}
render={() => <BasicSetupPage />}
render={() => <SetupPage />}
/>
<Route
exact

View File

@@ -1,48 +0,0 @@
import { useEffect } from "react";
import type { ISetupStep, ISetupStepBodyProps } from "../types";
import { Link } from "@mui/material";
import InlineOpenInNewIcon from "@src/components/InlineOpenInNewIcon";
import SetupItem from "../SetupItem";
import SignInWithGoogle from "../SignInWithGoogle";
import { WIKI_LINKS } from "@src/constants/externalLinks";
import { useAppContext } from "@src/contexts/AppContext";
export default {
id: "oauth",
shortTitle: "Access",
title: "Allow Firebase access",
description: (
<>
Allow Rowy to manage your Firebase Authentication, Firestore database, and
Firebase Storage.
<br />
<br />
Your data and code always stays on your Firebase project.{" "}
<Link href={WIKI_LINKS.setup} target="_blank" rel="noopener noreferrer">
Learn more
<InlineOpenInNewIcon />
</Link>
</>
),
body: StepOauth,
} as ISetupStep;
function StepOauth({ isComplete, setComplete }: ISetupStepBodyProps) {
const { currentUser } = useAppContext();
useEffect(() => {
if (currentUser && !isComplete) setComplete();
}, [currentUser, isComplete, setComplete]);
return (
<SetupItem
title="Sign in with a Google account that has access to your Firebase project."
status="incomplete"
>
<SignInWithGoogle />
</SetupItem>
);
}

View File

@@ -1,74 +0,0 @@
import { ISetupStep, ISetupStepBodyProps } from "../types";
import {
useMediaQuery,
Typography,
Stack,
TextField,
MenuItem,
Divider,
Button,
} from "@mui/material";
import InlineOpenInNewIcon from "@src/components/InlineOpenInNewIcon";
import SetupItem from "../SetupItem";
export default {
id: "project",
shortTitle: "Project",
title: "Select project",
description: "Select which Firebase project to set up Rowy on.",
body: StepProject,
} as ISetupStep;
function StepProject({ isComplete, setComplete }: ISetupStepBodyProps) {
const isMobile = useMediaQuery((theme: any) => theme.breakpoints.down("md"));
return (
<SetupItem
title="Select an existing project or create a new one."
status="incomplete"
>
<Stack
spacing={2}
direction={isMobile ? "column" : "row"}
justifyContent="flex-start"
alignItems="center"
>
<TextField
label="Project"
select
fullWidth
style={isMobile ? undefined : { minWidth: 300 }}
helperText={isMobile ? undefined : " "}
SelectProps={{
displayEmpty: true,
renderValue: (v: any) =>
v || (
<Typography color="text.disabled">Select a project</Typography>
),
}}
onChange={() => setComplete()}
>
<MenuItem value="rowyio">rowyio</MenuItem>
<MenuItem value="rowy-service">rowy-service</MenuItem>
<MenuItem value="tryrowy">tryrowy</MenuItem>
<MenuItem value="rowy-cms-test">rowy-cms-test</MenuItem>
<MenuItem value="rowy-run">rowy-run</MenuItem>
</TextField>
<Divider orientation={isMobile ? "horizontal" : "vertical"} flexItem>
OR
</Divider>
<Button
onClick={() => setComplete()}
style={isMobile ? undefined : { minWidth: 300 }}
>
Create project in Firebase Console
<InlineOpenInNewIcon />
</Button>
</Stack>
</SetupItem>
);
}

View File

@@ -1,375 +0,0 @@
import { useState, useEffect } from "react";
import type { ISetupStep, ISetupStepBodyProps } from "../types";
import {
Typography,
FormControlLabel,
Checkbox,
Button,
Link,
Grid,
} from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton";
import InfoIcon from "@mui/icons-material/InfoOutlined";
import CopyIcon from "@src/assets/icons/Copy";
import InlineOpenInNewIcon from "@src/components/InlineOpenInNewIcon";
import SetupItem from "../SetupItem";
import DiffEditor from "@src/components/CodeEditor/DiffEditor";
import { useAppContext } from "@src/contexts/AppContext";
import { CONFIG } from "@src/config/dbPaths";
import {
RULES_START,
RULES_END,
REQUIRED_RULES,
ADMIN_RULES,
RULES_UTILS,
INSECURE_RULES,
} from "@src/config/firestoreRules";
import { rowyRun } from "@src/utils/rowyRun";
import { runRoutes } from "@src/constants/runRoutes";
// import { useConfirmation } from "@src/components/ConfirmationDialog";
export default {
id: "rules",
shortTitle: "Firestore rules",
title: "Set up Firestore rules",
description: (
<>
Rowy configuration is stored in the <code>{CONFIG}</code> collection on
Firestore. Your users will need read access to this collection and admins
will need write access.
</>
),
body: StepRules,
} as ISetupStep;
const insecureRuleRegExp = new RegExp(
INSECURE_RULES.replace(/\//g, "\\/")
.replace(/\*/g, "\\*")
.replace(/\s{2,}/g, "\\s+")
.replace(/\s/g, "\\s*")
.replace(/\n/g, "\\s+")
.replace(/;/g, ";?")
);
function StepRules({
rowyRunUrl,
isComplete,
setComplete,
}: ISetupStepBodyProps & { rowyRunUrl: string }) {
const { projectId, getAuthToken } = useAppContext();
// const { requestConfirmation } = useConfirmation();
const [error, setError] = useState<string | false>(false);
const [hasRules, setHasRules] = useState(isComplete);
const [adminRule, setAdminRule] = useState(true);
const [showManualMode, setShowManualMode] = useState(false);
const rules = (adminRule ? ADMIN_RULES : "") + REQUIRED_RULES + RULES_UTILS;
const [currentRules, setCurrentRules] = useState("");
useEffect(() => {
if (rowyRunUrl && !hasRules && !currentRules)
getAuthToken(true)
.then((authToken) =>
rowyRun({
serviceUrl: rowyRunUrl,
route: runRoutes.firestoreRules,
authToken,
})
)
.then((data) => {
if (data?.code) {
setError(data.code);
setShowManualMode(true);
} else {
setCurrentRules(data?.source?.[0]?.content ?? "");
}
});
}, [rowyRunUrl, hasRules, currentRules, getAuthToken]);
const hasInsecureRule = insecureRuleRegExp.test(currentRules);
const [newRules, setNewRules] = useState("");
useEffect(() => {
if (!currentRules) {
setNewRules(RULES_START + rules + RULES_END);
} else {
let rulesToInsert = rules;
if (currentRules.indexOf("function isDocOwner") > -1) {
rulesToInsert = rulesToInsert.replace(/function isDocOwner[^}]*}/s, "");
}
if (currentRules.indexOf("function hasAnyRole") > -1) {
rulesToInsert = rulesToInsert.replace(/function hasAnyRole[^}]*}/s, "");
}
let inserted = currentRules.replace(
/match\s*\/databases\/\{database\}\/documents\s*\{/,
`match /databases/{database}/documents {\n` + rulesToInsert
);
if (hasInsecureRule) inserted = inserted.replace(insecureRuleRegExp, "");
setNewRules(inserted);
}
}, [currentRules, rules, hasInsecureRule]);
const [rulesStatus, setRulesStatus] = useState<"LOADING" | string>("");
const setRules = async () => {
setRulesStatus("LOADING");
try {
const authToken = await getAuthToken();
if (!authToken) throw new Error("Failed to generate auth token");
const res = await rowyRun({
serviceUrl: rowyRunUrl,
route: runRoutes.setFirestoreRules,
authToken,
body: { ruleset: newRules },
});
if (!res.success) throw new Error(res.message);
const isSuccessful = await checkRules(rowyRunUrl, authToken);
if (isSuccessful) {
setComplete();
setHasRules(true);
}
setRulesStatus("");
} catch (e: any) {
console.error(e);
setRulesStatus(e.message);
}
};
const verifyRules = async () => {
setRulesStatus("LOADING");
try {
const authToken = await getAuthToken();
if (!authToken) throw new Error("Failed to generate auth token");
const isSuccessful = await checkRules(rowyRunUrl, authToken);
if (isSuccessful) {
setComplete();
setHasRules(true);
}
setRulesStatus("");
} catch (e: any) {
console.error(e);
setRulesStatus(e.message);
}
};
// const handleSkip = () => {
// requestConfirmation({
// title: "Skip rules",
// body: "This might prevent you or other users in your project from accessing firestore data on Rowy",
// confirm: "Skip",
// cancel: "cancel",
// handleConfirm: async () => {
// setComplete();
// setHasRules(true);
// },
// });
// };
return (
<>
{!hasRules && error !== "security-rules/not-found" && (
<SetupItem
status="incomplete"
title="Add the following rules to enable access to Rowy configuration:"
>
<FormControlLabel
control={
<Checkbox
checked={adminRule}
onChange={(e) => setAdminRule(e.target.checked)}
/>
}
label="Allow admins to read and write all documents"
sx={{ "&&": { ml: -11 / 8, mb: -11 / 8 }, width: "100%" }}
/>
{hasInsecureRule && (
<Typography>
<InfoIcon
aria-label="Info"
sx={{ fontSize: 18, mr: 11 / 8, verticalAlign: "sub" }}
/>
We removed an insecure rule that allows anyone to access any part
of your database
</Typography>
)}
<DiffEditor
original={currentRules}
modified={newRules}
containerProps={{ sx: { width: "100%" } }}
minHeight={400}
options={{ renderValidationDecorations: "off" }}
/>
<Typography
variant="inherit"
color={
rulesStatus !== "LOADING" && rulesStatus ? "error" : undefined
}
>
Please verify the new rules are valid first.
</Typography>
<LoadingButton
variant="contained"
color="primary"
// TODO: onClick={setRules}
onClick={() => setComplete()}
loading={rulesStatus === "LOADING"}
style={{ position: "sticky", bottom: 8 }}
>
Set Firestore rules
</LoadingButton>
{rulesStatus !== "LOADING" && typeof rulesStatus === "string" && (
<Typography variant="caption" color="error">
{rulesStatus}
</Typography>
)}
{!showManualMode && (
<Link
component="button"
variant="body2"
onClick={() => setShowManualMode(true)}
>
Alternatively, add these rules in the Firebase Console
</Link>
)}
</SetupItem>
)}
{!hasRules && showManualMode && (
<>
<SetupItem
status="incomplete"
title={
error === "security-rules/not-found"
? "Add the following rules in the Firebase Console to enable access to Rowy configuration:"
: "Alternatively, you can add these rules in the Firebase Console."
}
>
<Typography
variant="caption"
component="pre"
sx={{
width: "100%",
height: 400,
resize: "both",
overflow: "auto",
"& .comment": { color: "info.dark" },
}}
dangerouslySetInnerHTML={{
__html: rules.replace(
/(\/\/.*$)/gm,
`<span class="comment">$1</span>`
),
}}
/>
<div>
<Grid container spacing={1}>
<Grid item>
<Button
startIcon={<CopyIcon />}
onClick={() => navigator.clipboard.writeText(rules)}
>
Copy to clipboard
</Button>
</Grid>
<Grid item>
<Button
variant="contained"
color="primary"
href={`https://console.firebase.google.com/project/${
projectId || "_"
}/firestore/rules`}
target="_blank"
rel="noopener noreferrer"
>
Set up in Firebase Console
<InlineOpenInNewIcon />
</Button>
</Grid>
<Grid item>
{rulesStatus !== "LOADING" &&
typeof rulesStatus === "string" && (
<Typography variant="caption" color="error">
{rulesStatus}
</Typography>
)}
</Grid>
</Grid>
</div>
</SetupItem>
<SetupItem
status="incomplete"
title={
<LoadingButton
variant="contained"
color="primary"
onClick={verifyRules}
loading={rulesStatus === "LOADING"}
>
Verify
</LoadingButton>
}
>
{rulesStatus !== "LOADING" && typeof rulesStatus === "string" && (
<Typography variant="caption" color="error">
{rulesStatus}
</Typography>
)}
</SetupItem>
</>
)}
{hasRules && (
<SetupItem status="complete" title="Firestore rules are set up." />
)}
</>
);
}
export const checkRules = async (
rowyRunUrl: string,
authToken: string,
signal?: AbortSignal
) => {
if (!authToken) return false;
try {
const res = await rowyRun({
serviceUrl: rowyRunUrl,
route: runRoutes.firestoreRules,
authToken,
signal,
});
const rules = res?.source?.[0]?.content || "";
if (!rules) return false;
const sanitizedRules = rules.replace(/\s{2,}/g, " ").replace(/\n/g, " ");
const hasRules =
sanitizedRules.includes(
REQUIRED_RULES.replace(/\s{2,}/g, " ").replace(/\n/g, " ")
) &&
sanitizedRules.includes(
RULES_UTILS.replace(/\s{2,}/g, " ").replace(/\n/g, " ")
);
return hasRules;
} catch (e: any) {
console.error(e);
return false;
}
};

View File

@@ -1,63 +0,0 @@
import { useSnackbar } from "notistack";
import type { ISetupStep, ISetupStepBodyProps } from "../types";
import { Typography, Button, Grid } from "@mui/material";
import CopyIcon from "@src/assets/icons/Copy";
import InlineOpenInNewIcon from "@src/components/InlineOpenInNewIcon";
import DoneIcon from "@mui/icons-material/Done";
import SetupItem from "../SetupItem";
import DiffEditor from "@src/components/CodeEditor/DiffEditor";
import { useAppContext } from "@src/contexts/AppContext";
import {
RULES_START,
RULES_END,
REQUIRED_RULES,
} from "@src/config/storageRules";
export default {
id: "storageRules",
shortTitle: "Storage rules",
title: "Set up Firebase Storage rules",
description:
"Image and File fields store files in Firebase Storage. Your users will need read and write access.",
body: StepStorageRules,
} as ISetupStep;
const rules = RULES_START + REQUIRED_RULES + RULES_END;
function StepStorageRules({ isComplete, setComplete }: ISetupStepBodyProps) {
const { projectId } = useAppContext();
const { enqueueSnackbar } = useSnackbar();
return (
<>
<SetupItem
status="incomplete"
title="Add the following rules to allow users to access Firebase Storage:"
>
<DiffEditor
original=""
modified={rules}
containerProps={{ sx: { width: "100%" } }}
minHeight={400}
options={{ renderValidationDecorations: "off" }}
/>
<Typography variant="inherit">
Please verify the new rules are valid first.
</Typography>
<Button
variant="contained"
color="primary"
onClick={() => setComplete()}
sx={{ mt: -0.5 }}
>
Set Firebase Storage rules
</Button>
</SetupItem>
</>
);
}

View File

@@ -1,91 +0,0 @@
import type { ISetupStep, ISetupStepBodyProps } from "../types";
import {
FormControlLabel,
Checkbox,
Typography,
Link,
Button,
} from "@mui/material";
import { EXTERNAL_LINKS } from "@src/constants/externalLinks";
export default {
id: "welcome",
layout: "centered",
shortTitle: "Welcome",
title: "Welcome",
description: (
<>
Get started with Rowy in just a few minutes.
<br />
<br />
We have no access to your data and it always stays on your Firebase
project.
</>
),
body: StepWelcome,
} as ISetupStep;
function StepWelcome({ isComplete, setComplete }: ISetupStepBodyProps) {
return (
<>
<FormControlLabel
control={
<Checkbox
checked={isComplete}
onChange={(e) => setComplete(e.target.checked)}
/>
}
label={
<>
I agree to the{" "}
<Link
href={EXTERNAL_LINKS.terms}
target="_blank"
rel="noopener noreferrer"
variant="body2"
color="text.primary"
>
Terms and Conditions
</Link>{" "}
and{" "}
<Link
href={EXTERNAL_LINKS.privacy}
target="_blank"
rel="noopener noreferrer"
variant="body2"
color="text.primary"
>
Privacy Policy
</Link>
</>
}
sx={{
pr: 1,
textAlign: "left",
alignItems: "flex-start",
p: 0,
m: 0,
}}
/>
<Button
variant="contained"
color="primary"
size="large"
disabled={!isComplete}
type="submit"
>
Get started
</Button>
<div>
<Typography variant="body2" paragraph sx={{ mt: 4 }}>
Want to invite your teammate to help with setup instead?
</Typography>
<Button>Send to teammate</Button>
</div>
</>
);
}

View File

@@ -1,217 +0,0 @@
import { useState, useEffect } from "react";
import { useLocation, useHistory } from "react-router-dom";
import queryString from "query-string";
import type { ISetupStep, ISetupStepBodyProps } from "../types";
import { Button, Typography, Stack, TextField } from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton";
import InlineOpenInNewIcon from "@src/components/InlineOpenInNewIcon";
import SetupItem from "../SetupItem";
import { rowyRun } from "@src/utils/rowyRun";
import { runRoutes } from "@src/constants/runRoutes";
import { EXTERNAL_LINKS, WIKI_LINKS } from "@src/constants/externalLinks";
export default {
id: "rowyRun",
shortTitle: "Rowy Run",
title: "Set up Rowy Run",
description:
"Rowy Run is a Google Cloud Run instance that provides backend functionality, such as table action scripts, user management, and easy Cloud Function deployment.",
body: StepRowyRun,
} as ISetupStep;
function StepRowyRun({
isComplete,
setComplete,
}: // rowyRunUrl: paramsRowyRunUrl,
ISetupStepBodyProps) {
const { pathname } = useLocation();
const history = useHistory();
const [isValidRowyRunUrl, setIsValidRowyRunUrl] = useState(isComplete);
const [isLatestVersion, setIsLatestVersion] = useState(isComplete);
const [rowyRunUrl, setRowyRunUrl] = useState("paramsRowyRunUrl");
const [latestVersion, setLatestVersion] = useState("");
const [verificationStatus, setVerificationStatus] = useState<
"IDLE" | "LOADING" | "FAIL"
>("IDLE");
const verifyRowyRun = async () => {
setVerificationStatus("LOADING");
try {
const result = await checkRowyRun(rowyRunUrl);
setVerificationStatus("IDLE");
if (result.isValidRowyRunUrl) setIsValidRowyRunUrl(true);
setLatestVersion(result.latestVersion);
if (result.isLatestVersion) {
setIsLatestVersion(true);
setComplete();
history.replace({
pathname,
search: queryString.stringify({ rowyRunUrl }),
});
}
} catch (e: any) {
console.error(`Failed to verify Rowy Run URL: ${e}`);
setVerificationStatus("FAIL");
}
};
// useEffect(() => {
// if (!isValidRowyRunUrl && paramsRowyRunUrl) console.log(paramsRowyRunUrl);
// }, [paramsRowyRunUrl, isValidRowyRunUrl]);
const deployButton = window.location.hostname.includes(
EXTERNAL_LINKS.rowyAppHostName
) ? (
<a
href={EXTERNAL_LINKS.rowyRunDeploy}
target="_blank"
rel="noopener noreferrer"
>
<img
src="https://deploy.cloud.run/button.svg"
alt="Run on Google Cloud"
width={183}
height={32}
style={{ display: "block" }}
/>
</a>
) : (
<Button href={WIKI_LINKS.rowyRun} target="_blank" rel="noopener noreferrer">
Deploy instructions
<InlineOpenInNewIcon />
</Button>
);
return (
<>
<SetupItem
status={isValidRowyRunUrl ? "complete" : "incomplete"}
title={
isValidRowyRunUrl
? `Rowy Run is set up at: ${rowyRunUrl}`
: "Deploy Rowy Run to your Google Cloud project."
}
>
{!isValidRowyRunUrl && (
<>
{deployButton}
<div>
<Typography variant="inherit" gutterBottom>
Then paste the Rowy Run instance URL below:
</Typography>
<Stack
direction="row"
spacing={1}
alignItems="center"
style={{ width: "100%" }}
>
<TextField
id="rowyRunUrl"
label="Rowy Run instance URL"
placeholder="https://rowy-backend-*.run.app"
value={rowyRunUrl}
onChange={(e) => setRowyRunUrl(e.target.value)}
type="url"
autoComplete="url"
fullWidth
error={verificationStatus === "FAIL"}
helperText={
verificationStatus === "FAIL" ? "Invalid URL" : " "
}
/>
<LoadingButton
variant="contained"
color="primary"
loading={verificationStatus === "LOADING"}
onClick={verifyRowyRun}
>
Verify
</LoadingButton>
</Stack>
</div>
</>
)}
</SetupItem>
{isValidRowyRunUrl && (
<SetupItem
status={isLatestVersion ? "complete" : "incomplete"}
title={
isLatestVersion
? latestVersion
? `Rowy Run is up to date: ${latestVersion}`
: "Rowy Run is up to date."
: `Update your Rowy Run instance. Latest version: ${latestVersion}`
}
>
{!isLatestVersion && (
<Stack direction="row" spacing={1} alignItems="center">
{deployButton}
<LoadingButton
variant="contained"
color="primary"
loading={verificationStatus === "LOADING"}
onClick={verifyRowyRun}
>
Verify
</LoadingButton>
</Stack>
)}
</SetupItem>
)}
</>
);
}
export const checkRowyRun = async (
serviceUrl: string,
signal?: AbortSignal
) => {
const result = {
isValidRowyRunUrl: false,
isLatestVersion: false,
latestVersion: "",
};
try {
const res = await rowyRun({ serviceUrl, route: runRoutes.version, signal });
if (!res.version) return result;
result.isValidRowyRunUrl = true;
// https://docs.github.com/en/rest/reference/repos#get-the-latest-release
const endpoint =
EXTERNAL_LINKS.rowyRunGitHub.replace(
"github.com",
"api.github.com/repos"
) + "/releases/latest";
const latestVersionReq = await fetch(endpoint, {
headers: { Accept: "application/vnd.github.v3+json" },
signal,
});
const latestVersion = await latestVersionReq.json();
if (!latestVersion.tag_name) return result;
if (latestVersion.tag_name > "v" + res.version) {
result.isLatestVersion = false;
result.latestVersion = latestVersion.tag_name;
} else {
result.isLatestVersion = true;
result.latestVersion = res.version;
}
} catch (e: any) {
console.error(e);
} finally {
return result;
}
};

View File

@@ -1,14 +1,14 @@
import { useState } from "react";
import SetupLayout from "@src/components/Setup/SetupLayout";
import StepWelcome from "@src/components/Setup/BasicSetup/StepWelcome";
import StepRules from "@src/components/Setup/BasicSetup/StepRules";
import StepStorageRules from "@src/components/Setup/BasicSetup/StepStorageRules";
import StepFinish from "@src/components/Setup/BasicSetup/StepFinish";
import StepWelcome from "@src/components/Setup/Steps/StepWelcome";
import StepRules from "@src/components/Setup/Steps/StepRules";
import StepStorageRules from "@src/components/Setup/Steps/StepStorageRules";
import StepFinish from "@src/components/Setup/Steps/StepFinish";
const steps = [StepWelcome, StepRules, StepStorageRules, StepFinish];
export default function BasicSetupPage() {
export default function SetupPage() {
const [completion, setCompletion] = useState<Record<string, boolean>>({
welcome: false,
rules: false,

View File

@@ -1,34 +0,0 @@
import { useState } from "react";
import SetupLayout from "@src/components/Setup/SetupLayout";
import StepWelcome from "@src/components/Setup/RowyAppSetup/StepWelcome";
import StepOauth from "@src/components/Setup/RowyAppSetup/StepOauth";
import StepProject from "@src/components/Setup/RowyAppSetup/StepProject";
import StepRules from "@src/components/Setup/RowyAppSetup/StepRules";
import StepStorageRules from "@src/components/Setup/RowyAppSetup/StepStorageRules";
import StepFinish from "@src/components/Setup/BasicSetup/StepFinish";
const steps = [
StepWelcome,
StepOauth,
StepProject,
StepRules,
StepStorageRules,
StepFinish,
];
export default function RowyAppSetupPage() {
const [completion, setCompletion] = useState<Record<string, boolean>>({
welcome: false,
rules: false,
storageRules: false,
});
return (
<SetupLayout
steps={steps}
completion={completion}
setCompletion={setCompletion}
/>
);
}

View File

@@ -1,410 +0,0 @@
import { useState, useEffect } from "react";
import { use100vh } from "react-div-100vh";
import { SwitchTransition } from "react-transition-group";
import { useLocation, Link } from "react-router-dom";
import queryString from "query-string";
import {
useMediaQuery,
Paper,
Stepper,
Step,
StepButton,
MobileStepper,
IconButton,
Typography,
Stack,
DialogActions,
Button,
Tooltip,
} from "@mui/material";
import { alpha } from "@mui/material/styles";
import LoadingButton from "@mui/lab/LoadingButton";
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
import BrandedBackground, { Wrapper } from "@src/assets/BrandedBackground";
import Logo from "@src/assets/Logo";
import ScrollableDialogContent from "@src/components/Modal/ScrollableDialogContent";
import { SlideTransition } from "@src/components/Modal/SlideTransition";
import StepWelcome from "@src/components/Setup/RowyAppSetup/StepWelcome";
import Step1Oauth from "@src/components/Setup/Step1Oauth";
// prettier-ignore
import Step2ProjectOwner, { checkProjectOwner } from "@src/components/Setup/Step2ProjectOwner";
// import Step3Rules, { checkRules } from "@src/components/Setup/Step3Rules";
import Step4Migrate, { checkMigrate } from "@src/components/Setup/Step4Migrate";
import Step5Finish from "@src/components/Setup/Step6Finish";
import routes from "@src/constants/routes";
import { useAppContext } from "@src/contexts/AppContext";
import { analytics } from "analytics";
export interface ISetupStep {
id: string;
layout?: "centered";
shortTitle: string;
title: React.ReactNode;
description?: React.ReactNode;
body: React.ReactNode;
}
export interface ISetupStepBodyProps {
completion: Record<string, boolean>;
setCompletion: React.Dispatch<React.SetStateAction<Record<string, boolean>>>;
checkAllSteps: typeof checkAllSteps;
rowyRunUrl: string;
}
const BASE_WIDTH = 1024;
const checkAllSteps = async (
rowyRunUrl: string,
currentUser: firebase.default.User | null | undefined,
userRoles: string[] | null,
authToken: string,
signal: AbortSignal
) => {
console.log("Check all steps");
const completion: Record<string, boolean> = {};
// const rowyRunValidation = await checkRowyRun(rowyRunUrl, signal);
// if (rowyRunValidation.isValidRowyRunUrl) {
// if (rowyRunValidation.isLatestVersion) completion.rowyRun = true;
// const promises = [
// checkProjectOwner(rowyRunUrl, currentUser, userRoles, signal).then(
// (projectOwner) => {
// if (projectOwner) completion.projectOwner = true;
// }
// ),
// checkRules(rowyRunUrl, authToken, signal).then((rules) => {
// if (rules) completion.rules = true;
// }),
// checkMigrate(rowyRunUrl, authToken, signal).then((requiresMigration) => {
// if (requiresMigration) completion.migrate = false;
// }),
// ];
// await Promise.all(promises);
// }
return completion;
};
export default function SetupPage() {
const { currentUser, userRoles, getAuthToken } = useAppContext();
const fullScreenHeight = use100vh() ?? 0;
const isMobile = useMediaQuery((theme: any) => theme.breakpoints.down("sm"));
const { search } = useLocation();
const params = queryString.parse(search);
const rowyRunUrl = decodeURIComponent((params.rowyRunUrl as string) || "");
const [stepId, setStepId] = useState("welcome");
const [completion, setCompletion] = useState<Record<string, boolean>>({
welcome: false,
rowyRun: false,
serviceAccount: false,
projectOwner: false,
rules: false,
});
// const [checkingAllSteps, setCheckingAllSteps] = useState(false);
// useEffect(() => {
// const controller = new AbortController();
// const signal = controller.signal;
// if (rowyRunUrl) {
// setCheckingAllSteps(true);
// getAuthToken().then((authToken) =>
// checkAllSteps(
// rowyRunUrl,
// currentUser,
// userRoles,
// authToken,
// signal
// ).then((result) => {
// if (!signal.aborted) {
// setCompletion((c) => ({ ...c, ...result }));
// setCheckingAllSteps(false);
// }
// })
// );
// }
// return () => controller.abort();
// }, [rowyRunUrl, currentUser, userRoles, getAuthToken]);
const stepProps = { completion, setCompletion, checkAllSteps, rowyRunUrl };
const handleContinue = () => {
let nextIncompleteStepIndex = stepIndex + 1;
while (completion[steps[nextIncompleteStepIndex]?.id]) {
console.log("iteration", steps[nextIncompleteStepIndex]?.id);
nextIncompleteStepIndex++;
}
const nextStepId = steps[nextIncompleteStepIndex].id;
analytics.logEvent("setup_step", { step: nextStepId });
setStepId(nextStepId);
};
const steps: ISetupStep[] = [
{
id: "welcome",
layout: "centered" as "centered",
shortTitle: "Welcome",
title: `Welcome`,
body: <StepWelcome {...stepProps} />,
},
// {
// id: "rowyRun",
// shortTitle: `Rowy Run`,
// title: `Set up Rowy Run`,
// body: <Step1RowyRun {...stepProps} />,
// },
// {
// id: "projectOwner",
// shortTitle: `Project owner`,
// title: `Set up project owner`,
// body: <Step2ProjectOwner {...stepProps} />,
// },
{
id: "oauth",
shortTitle: `Access`,
title: `Allow Firebase access`,
body: <Step1Oauth {...stepProps} />,
},
{
id: "project",
shortTitle: `Project`,
title: `Select project`,
body: <Step1Oauth {...stepProps} />,
},
{
id: "rules",
shortTitle: `Firestore Rules`,
title: `Set up Firestore Rules`,
body: <Step1Oauth {...stepProps} />,
},
{
id: "storageRules",
shortTitle: `Storage Rules`,
title: `Set up Firestore Rules`,
body: <Step1Oauth {...stepProps} />,
},
{
id: "finish",
layout: "centered" as "centered",
shortTitle: `Finish`,
title: `Youre all set up!`,
body: <Step5Finish />,
// actions: (
// <Button
// variant="contained"
// color="primary"
// component={Link}
// to={routes.home}
// sx={{ ml: 1 }}
// >
// Continue to Rowy
// </Button>
// ),
},
];
const step =
steps.find((step) => step.id === (stepId || steps[0].id)) ?? steps[0];
const stepIndex = steps.findIndex(
(step) => step.id === (stepId || steps[0].id)
);
const listedSteps = steps.filter((step) => step.layout !== "centered");
return (
<Wrapper>
<BrandedBackground />
<Paper
component="main"
elevation={4}
sx={{
backgroundColor: (theme) =>
alpha(theme.palette.background.paper, 0.75),
backdropFilter: "blur(20px) saturate(150%)",
maxWidth: BASE_WIDTH,
width: (theme) => `calc(100vw - ${theme.spacing(2)})`,
height: (theme) =>
`calc(${
fullScreenHeight > 0 ? `${fullScreenHeight}px` : "100vh"
} - ${theme.spacing(
2
)} - env(safe-area-inset-top) - env(safe-area-inset-bottom))`,
resize: "both",
p: 0,
"& > *, & > .MuiDialogContent-root": { px: { xs: 2, sm: 4 } },
display: "flex",
flexDirection: "column",
"& .MuiTypography-inherit, & .MuiDialogContent-root": {
typography: "body1",
},
}}
>
{stepId === "welcome" ? null : !isMobile ? (
<Stepper
activeStep={stepIndex - 1}
nonLinear
sx={{
mt: 2.5,
mb: 3,
"& .MuiStep-root:first-child": { pl: 0 },
"& .MuiStep-root:last-child": { pr: 0 },
userSelect: "none",
}}
>
{listedSteps.map(({ id, shortTitle }, i) => (
<Step key={id} completed={completion[id]}>
<StepButton
onClick={() => setStepId(id)}
disabled={i > 0 && !completion[listedSteps[i - 1]?.id]}
sx={{ py: 2, my: -2, borderRadius: 1 }}
>
{shortTitle}
</StepButton>
</Step>
))}
</Stepper>
) : (
<MobileStepper
variant="dots"
steps={listedSteps.length}
activeStep={stepIndex - 1}
backButton={
<IconButton
aria-label="Previous step"
disabled={stepIndex === 0}
onClick={() => setStepId(steps[stepIndex - 1].id)}
>
<ChevronLeftIcon />
</IconButton>
}
nextButton={
<IconButton
aria-label="Next step"
disabled={!completion[stepId]}
onClick={() => setStepId(steps[stepIndex + 1].id)}
>
<ChevronRightIcon />
</IconButton>
}
position="static"
sx={{
background: "none",
p: 0,
"& .MuiMobileStepper-dot": { mx: 0.5 },
}}
/>
)}
{step.layout === "centered" ? (
<ScrollableDialogContent disableTopDivider>
<Stack
alignItems="center"
justifyContent="center"
spacing={3}
sx={{
minHeight: "100%",
maxWidth: 440,
margin: "0 auto",
textAlign: "center",
py: 3,
}}
>
{stepId === "welcome" && (
<SwitchTransition mode="out-in">
<SlideTransition key={stepId} appear timeout={50}>
<Logo size={2} />
</SlideTransition>
</SwitchTransition>
)}
<SwitchTransition mode="out-in">
<SlideTransition key={stepId} appear timeout={100}>
<Typography
variant="h4"
component="h1"
sx={{ mb: 1, typography: { xs: "h5", md: "h4" } }}
>
{step.title}
</Typography>
</SlideTransition>
</SwitchTransition>
<SwitchTransition mode="out-in">
<SlideTransition key={stepId} appear timeout={150}>
<Stack spacing={4} alignItems="center">
{step.body}
</Stack>
</SlideTransition>
</SwitchTransition>
</Stack>
</ScrollableDialogContent>
) : (
<>
<SwitchTransition mode="out-in">
<SlideTransition key={stepId} appear timeout={50}>
<Typography
variant="h4"
component="h1"
sx={{ mb: 1, typography: { xs: "h5", md: "h4" } }}
>
{step.title}
</Typography>
</SlideTransition>
</SwitchTransition>
<SwitchTransition mode="out-in">
<SlideTransition key={stepId} appear timeout={100}>
<ScrollableDialogContent
disableTopDivider={step.layout === "centered"}
sx={{ overflowX: "auto" }}
>
<Stack spacing={4}>{step.body}</Stack>
</ScrollableDialogContent>
</SlideTransition>
</SwitchTransition>
</>
)}
{step.layout !== "centered" && (
<form
onSubmit={(e) => {
e.preventDefault();
try {
handleContinue();
} catch (e: any) {
throw new Error(e.message);
}
return false;
}}
>
<DialogActions>
<Button
variant="contained"
color="primary"
size="large"
type="submit"
// loading={checkingAllSteps}
disabled={!completion[stepId]}
>
Continue
</Button>
</DialogActions>
</form>
)}
</Paper>
</Wrapper>
);
}