Skip to content

Commit

Permalink
chore: fix isEdit prop drilling and various routes
Browse files Browse the repository at this point in the history
  • Loading branch information
IanKrieger committed Aug 24, 2023
1 parent a8e5af9 commit a897a7e
Show file tree
Hide file tree
Showing 22 changed files with 88 additions and 138 deletions.
7 changes: 3 additions & 4 deletions src/components/Button/DashboardButton.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { Button } from "@mui/material";
import ArrowBack from "@mui/icons-material/ArrowBack";
import { useHistory } from "react-router-dom";
import { Link as RouterLink } from "react-router-dom";

export function DashboardButton() {
const history = useHistory();

return (
<Button
variant="text"
startIcon={<ArrowBack />}
onClick={() => history.replace("/user/main")}
component={RouterLink}
to="/user/main"
>
Dashboard
</Button>
Expand Down
15 changes: 0 additions & 15 deletions src/components/Button/DashboardIconButton.tsx

This file was deleted.

6 changes: 4 additions & 2 deletions src/components/Campaigns/CampaignDateRange.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import { useField } from "formik";
import { useState } from "react";
import { getDefaultTimezone, TimeZonePicker } from "../TimeZonePicker";
import { TimezoneAwareDatePicker } from "../TimeZonePicker/TimezoneAwareDatePicker";
import { useIsEdit } from "form/FormikHelpers";

export const CampaignDateRange = ({ isEdit }: { isEdit: boolean }) => {
export const CampaignDateRange = () => {
const { isEditAndDraft } = useIsEdit();
const [tz, setTz] = useState<string>(getDefaultTimezone());
const [, startMeta, startHelper] = useField("startAt");
const [, endMeta, endHelper] = useField("endAt");
Expand All @@ -25,7 +27,7 @@ export const CampaignDateRange = ({ isEdit }: { isEdit: boolean }) => {
startHelper.setValue(formatISO(dt));
startHelper.setTouched(true);
}}
disabled={isEdit}
disabled={!isEditAndDraft}
/>

<ArrowForwardIcon />
Expand Down
8 changes: 3 additions & 5 deletions src/components/Navigation/DraftMenu.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { useContext, useState, MouseEvent } from "react";

import { useHistory } from "react-router-dom";
import { Link as RouterLink } from "react-router-dom";
import { Badge, Button, Menu, MenuItem } from "@mui/material";
import { DraftContext } from "state/context";

export function DraftMenu() {
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const history = useHistory();
const { drafts } = useContext(DraftContext);

const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
Expand Down Expand Up @@ -46,10 +45,9 @@ export function DraftMenu() {
{drafts.map((d, idx) => (
<MenuItem
key={`draft-${d.draftId}-${idx}`}
component={RouterLink}
to={`/user/main/adsmanager/advanced/new/${d.draftId}/settings`}
onClick={() => {
history.push(
`/user/main/adsmanager/advanced/new/${d.draftId}/settings`,
);
setAnchorEl(null);
}}
sx={{ pt: 1, pb: 1, minWidth: "250px" }}
Expand Down
6 changes: 3 additions & 3 deletions src/components/Navigation/Navbar.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useHistory, useRouteMatch } from "react-router-dom";
import { useRouteMatch, Link as RouterLink } from "react-router-dom";

import { AppBar, Button, Divider, Stack, Toolbar } from "@mui/material";

Expand All @@ -11,7 +11,6 @@ import { useSignOut } from "auth/hooks/mutations/useSignOut";
export function Navbar() {
const { signOut } = useSignOut();
const { advertiser } = useAdvertiser();
const history = useHistory();
const { url } = useRouteMatch();
const isNewCampaignPage = url.includes("/user/main/adsmanager/advanced");
const isCompletePage = url.includes("/user/main/complete/new");
Expand Down Expand Up @@ -39,7 +38,8 @@ export function Navbar() {
<div style={{ flexGrow: 1 }} />
{advertiser.selfServiceCreate && (
<Button
onClick={() => history.push(newUrl)}
component={RouterLink}
to={newUrl}
size="medium"
variant="contained"
sx={{ mr: 3 }}
Expand Down
4 changes: 2 additions & 2 deletions src/components/Steps/ActionButtons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function ActionButtons() {
component={RouterLink}
size="small"
color="error"
to="/user/main"
to="/user/main/campaign"
onClick={() => {
localStorage.removeItem(values.draftId!);
setDrafts();
Expand All @@ -31,7 +31,7 @@ export function ActionButtons() {
<Button
size="small"
component={RouterLink}
to="/user/main"
to="/user/main/campaign"
startIcon={<ArrowBackIcon />}
>
Return to dashboard
Expand Down
2 changes: 1 addition & 1 deletion src/components/Steps/StepDrawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export function StepDrawer({
<Step key={step.label} completed={activeStep.current > index}>
<StepButton
onClick={() => {
history.push(`${step.path}${step.queryParams ?? ""}`);
history.replace(`${step.path}${step.queryParams ?? ""}`);
activeStep.current = index;
}}
>
Expand Down
35 changes: 9 additions & 26 deletions src/form/FormikHelpers.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
HTMLInputTypeAttribute,
PropsWithChildren,
ReactNode,
useEffect,
} from "react";
import { HTMLInputTypeAttribute, PropsWithChildren, ReactNode } from "react";
import {
Box,
Button,
Expand All @@ -20,8 +15,8 @@ import {
TooltipProps,
} from "@mui/material";
import { ErrorMessage, useField, useFormikContext } from "formik";
import { useHistory } from "react-router-dom";
import _ from "lodash";
import { CampaignForm } from "user/views/adsManager/types";

type FormikTextFieldProps = TextFieldProps & {
name: string;
Expand Down Expand Up @@ -158,7 +153,6 @@ interface FormikSubmitButtonProps {
label?: string;
inProgressLabel?: string;
isCreate: boolean;
allowNavigation?: boolean;
}

function extractErrors(errorObject: any): string[] {
Expand All @@ -171,29 +165,11 @@ export const FormikSubmitButton = ({
label = "Save",
inProgressLabel = "Saving...",
isCreate,
allowNavigation,
}: FormikSubmitButtonProps) => {
const formik = useFormikContext();
const history = useHistory();

let saveButtonTooltip: TooltipProps["title"] = "";
let saveEnabled = true;

// On create, the save button is initially enabled so the user can click it
// to see the full set of validation errors.
// On edit, it should only be enabled once they've made changes.
useEffect(() => {
const unblock = history.block(
!allowNavigation && formik.dirty
? "You’ve got unsaved changes. Are you sure you want to navigate away from this page?"
: true,
);

return function cleanup() {
unblock();
};
}, [formik.dirty, allowNavigation]);

if (formik.isSubmitting) {
saveEnabled = false;
} else if (!isCreate && !formik.dirty) {
Expand Down Expand Up @@ -232,3 +208,10 @@ export const FormikSubmitButton = ({
</Tooltip>
);
};

export function useIsEdit() {
const { values } = useFormikContext<CampaignForm>();
const isEdit = values.id !== undefined && values.id.trim() !== "";
const isEditAndDraft = isEdit && values.state === "draft";
return { isEdit, isEditAndDraft };
}
1 change: 1 addition & 0 deletions src/user/library/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ export function editCampaignValues(
const price = billingType === "cpm" ? rawPrice.multipliedBy(1000) : rawPrice;

return {
id: campaign.id,
adSets: campaign.adSets.map((adSet) => {
const seg = adSet.segments ?? ([] as Segment[]);

Expand Down
1 change: 1 addition & 0 deletions src/user/views/adsManager/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { IAdvertiser } from "auth/context/auth.interface";
export type Billing = "cpm" | "cpc" | "cpv";

export type CampaignForm = {
id?: string;
draftId?: string;
advertiserId: string;
startAt: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@ import { PickerFields } from "./fields/PickerFields";
import { ConversionField } from "./fields/ConversionField";
import { CardContainer } from "components/Card/CardContainer";
import { useHistory } from "react-router-dom";
import { FormikTextField } from "form/FormikHelpers";
import { FormikTextField, useIsEdit } from "form/FormikHelpers";
import { AdSetAds } from "user/views/adsManager/views/advanced/components/adSet/fields/AdSetAds";

interface Props {
isEdit: boolean;
}

export function AdSetFields({ isEdit }: Props) {
export function AdSetFields() {
const history = useHistory();
const { isEditAndDraft } = useIsEdit();
const params = new URLSearchParams(history.location.search);
const current = Number(params.get("current") ?? 0);
const fakeCurrent = current + 1;
Expand All @@ -27,7 +24,7 @@ export function AdSetFields({ isEdit }: Props) {

<PickerFields index={current} />

{!isEdit && <ConversionField index={current} />}
{isEditAndDraft && <ConversionField index={current} />}

<AdSetAds index={current} />
</>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ import { Link as RouterLink, useHistory } from "react-router-dom";
import { CampaignForm, initialAdSet } from "user/views/adsManager/types";
import { useRef } from "react";
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
import { useIsEdit } from "form/FormikHelpers";

export function NewAdSet(props: { isEdit: boolean }) {
export function NewAdSet() {
const { isEdit } = useIsEdit();
const history = useHistory();
const { values } = useFormikContext<CampaignForm>();
const params = new URLSearchParams(history.location.search);
Expand All @@ -34,7 +36,9 @@ export function NewAdSet(props: { isEdit: boolean }) {
<Link
component={RouterLink}
underline="none"
onClick={() => (selected.current = idx)}
onClick={() => {
selected.current = idx;
}}
to={`?current=${idx}`}
width="100%"
variant="overline"
Expand All @@ -51,7 +55,7 @@ export function NewAdSet(props: { isEdit: boolean }) {
{adSet.name || `Ad Set ${idx + 1}`}
</span>
</Link>
{idx > 0 && !props.isEdit && (
{idx > 0 && !adSet.id && (
<Tooltip title="Remove">
<IconButton
onClick={() => {
Expand All @@ -67,7 +71,7 @@ export function NewAdSet(props: { isEdit: boolean }) {
)}
</Stack>
))}
{values.adSets.length <= 4 && !props.isEdit && (
{values.adSets.length <= 4 && !isEdit && (
<Box
width="100%"
pb={0}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { BudgetField } from "user/views/adsManager/views/advanced/components/campaign/fields/BudgetField";
import { PaymentMethodField } from "user/views/adsManager/views/advanced/components/campaign/fields/PaymentMethodField";

export function BudgetSettings(props: { isEdit: boolean }) {
export function BudgetSettings() {
return (
<>
<BudgetField isEdit={props.isEdit} />
<BudgetField />

<PaymentMethodField isEdit={props.isEdit} />
<PaymentMethodField />
</>
);
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import { FormikTextField } from "form/FormikHelpers";
import { FormikTextField, useIsEdit } from "form/FormikHelpers";
import { CardContainer } from "components/Card/CardContainer";
import { CampaignDateRange } from "components/Campaigns/CampaignDateRange";
import { LocationField } from "user/views/adsManager/views/advanced/components/campaign/fields/LocationField";
import { Typography } from "@mui/material";
import { useFormikContext } from "formik";
import { CampaignForm } from "user/views/adsManager/types";

export function CampaignSettings(props: { isEdit: boolean }) {
const { values } = useFormikContext<CampaignForm>();
const isEdit = props.isEdit && values.state !== "draft";
export function CampaignSettings() {
const { isEditAndDraft } = useIsEdit();

return (
<>
Expand All @@ -19,10 +16,10 @@ export function CampaignSettings(props: { isEdit: boolean }) {

<FormikTextField name="name" label="Campaign Name" sx={{ mb: 1 }} />

<CampaignDateRange isEdit={isEdit} />
<CampaignDateRange />
</CardContainer>

{!isEdit && <LocationField />}
{isEditAndDraft && <LocationField />}
</>
);
}
Loading

0 comments on commit a897a7e

Please sign in to comment.