Skip to content

Commit

Permalink
refactor: Follow up type fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
DafyddLlyr committed Oct 1, 2024
1 parent 1743c8d commit 0a1cbc6
Show file tree
Hide file tree
Showing 14 changed files with 44 additions and 36 deletions.
6 changes: 3 additions & 3 deletions editor.planx.uk/src/@planx/components/FileUpload/Public.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import ErrorWrapper from "ui/shared/ErrorWrapper";
import { PASSPORT_REQUESTED_FILES_KEY } from "../FileUploadAndLabel/model";
import { PrivateFileUpload } from "../shared/PrivateFileUpload/PrivateFileUpload";
import { getPreviouslySubmittedData, makeData } from "../shared/utils";
import { FileUploadSlot, Props, slotsSchema } from "./model";
import { FileUpload, FileUploadSlot, slotsSchema } from "./model";

const FileUpload: React.FC<Props> = (props) => {
const FileUploadComponent: React.FC<FileUpload> = (props) => {
const recoveredSlots = getPreviouslySubmittedData(props)?.map(
(slot: FileUploadSlot) => slot.cachedSlot,
);
Expand Down Expand Up @@ -96,4 +96,4 @@ const FileUpload: React.FC<Props> = (props) => {
);
};

export default FileUpload;
export default FileUploadComponent;
2 changes: 1 addition & 1 deletion editor.planx.uk/src/@planx/components/FileUpload/model.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { HandleSubmit } from "pages/Preview/Node";
import { FileWithPath } from "react-dropzone";
import { array } from "yup";

export interface Props extends MoreInformation {
export interface FileUpload extends MoreInformation {
id?: string;
title?: string;
fn: string;
Expand Down
13 changes: 6 additions & 7 deletions editor.planx.uk/src/@planx/components/Pay/Public/Pay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import {
GovUKPayment,
PaymentStatus,
} from "@opensystemslab/planx-core/types";
import { PublicProps } from "@planx/components/ui";
import { logger } from "airbrake";
import axios from "axios";
import DelayedLoadingIndicator from "components/DelayedLoadingIndicator";
import { setLocalFlow } from "lib/local.new";
import { useStore } from "pages/FlowEditor/lib/store";
import { HandleSubmit } from "pages/Preview/Node";
import React, { useEffect, useReducer } from "react";
import { useErrorHandler } from "react-error-boundary";
import type { Session } from "types";
Expand All @@ -18,9 +18,7 @@ import { createPayload, GOV_UK_PAY_URL, Pay, toDecimal } from "../model";
import Confirm from "./Confirm";

export default Component;
interface Props extends Pay {
handleSubmit: HandleSubmit;
}
export type Props = PublicProps<Pay>;

type ComponentState =
| { status: "indeterminate"; displayText?: string }
Expand Down Expand Up @@ -119,7 +117,7 @@ function Component(props: Props) {
useEffect(() => {
// Auto-skip component when fee=0
if (fee <= 0) {
return props.handleSubmit({ auto: true });
return props.handleSubmit && props.handleSubmit({ auto: true });
}

// If props.fn is undefined, display & log an error
Expand All @@ -144,7 +142,8 @@ function Component(props: Props) {

const handleSuccess = () => {
dispatch(Action.Success);
props.handleSubmit(makeData(props, govUkPayment, GOV_PAY_PASSPORT_KEY));
props.handleSubmit &&
props.handleSubmit(makeData(props, govUkPayment, GOV_PAY_PASSPORT_KEY));
};

const normalizePaymentResponse = (responseData: any): GovUKPayment => {
Expand Down Expand Up @@ -282,7 +281,7 @@ function Component(props: Props) {
onConfirm={() => {
if (props.hidePay || state.status === "unsupported_team") {
// Show "Continue" button to proceed
props.handleSubmit({ auto: false });
props.handleSubmit && props.handleSubmit({ auto: false });
} else if (state.status === "init") {
startNewPayment();
} else if (state.status === "retry") {
Expand Down
2 changes: 1 addition & 1 deletion editor.planx.uk/src/@planx/components/Question/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export interface Question {
definitionImg?: string;
img?: string;
responses: {
id: string;
id?: string;
responseKey: string | number;
title: string;
description?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,9 @@ const ResultReason: React.FC<IResultReason> = ({
}
}, [summaryRef]);

const hasMoreInfo = question.data.info ?? question.data.policyRef;
const hasMoreInfo = question.data?.info ?? question.data?.policyRef;

const ariaLabel = `${question.data.text}: Your answer was: ${response}. ${
const ariaLabel = `${question.data?.text}: Your answer was: ${response}. ${
hasMoreInfo
? "Click to expand for more information about this question."
: ""
Expand Down Expand Up @@ -194,22 +194,22 @@ const ResultReason: React.FC<IResultReason> = ({
color="textPrimary"
id={`questionText-${id}`}
>
{question.data.text} <br />
{question.data?.text} <br />
<strong>{response}</strong>
</Typography>
</SummaryWrap>
</StyledAccordionSummary>
<AccordionDetails sx={{ py: 1, px: 0 }}>
<MoreInfo>
{question.data.info && (
{question.data?.info && (
<ReactMarkdownOrHtml
source={question.data.info}
source={question.data?.info}
openLinksOnNewTab
/>
)}
{question.data.policyRef && (
{question.data?.policyRef && (
<ReactMarkdownOrHtml
source={question.data.policyRef}
source={question.data?.policyRef}
openLinksOnNewTab
/>
)}
Expand All @@ -223,7 +223,7 @@ const ResultReason: React.FC<IResultReason> = ({
color="textPrimary"
id={`questionText-${id}`}
>
{question.data.text} <br />
{question.data?.text} <br />
<strong>{response}</strong>
</Typography>
</NonExpandingSummary>
Expand All @@ -239,7 +239,7 @@ const ResultReason: React.FC<IResultReason> = ({
>
Change
<span style={visuallyHidden}>
your response to {question.data.text || "this question"}
your response to {question.data?.text || "this question"}
</span>
</Link>
)}
Expand Down
8 changes: 7 additions & 1 deletion editor.planx.uk/src/@planx/components/TaskList/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ export interface TaskList extends MoreInformation {
title: string;
description?: string;
tasks: Array<Task>;
/**
* @deprecated Remove once migrated
*/
taskList?: {
tasks: Array<Task>;
};
}

export interface Task {
Expand All @@ -15,7 +21,7 @@ export interface Task {
export const parseTaskList = (
data: Record<string, any> | undefined,
): TaskList => ({
tasks: /* remove once migrated */ data?.taskList?.tasks || data?.tasks || [],
tasks: data?.taskList?.tasks || data?.tasks || [],
title: data?.title || "",
description: data?.description || "",
...parseMoreInformation(data),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -385,19 +385,19 @@ function Question(props: ComponentProps) {
function getNodeText() {
try {
const answerId = getAnswers(props)[0];
return props.flow[answerId].data.text;
return props.flow[answerId].data?.text;
} catch (err) {
return "";
}
}
}

function FindProperty(props: ComponentProps) {
const { source } = props.passport.data?._address;
const { source } = props.passport.data?._address || {};

if (source === "os") {
const { postcode, single_line_address, town } =
props.passport.data?._address;
props.passport.data?._address || {};
return (
<>
<Box component="dt">{FIND_PROPERTY_DT}</Box>
Expand Down Expand Up @@ -432,7 +432,7 @@ function Checklist(props: ComponentProps) {
<Box component="dd">
<ul>
{getAnswers(props).map((nodeId, i: number) => (
<li key={i}>{props.flow[nodeId].data.text}</li>
<li key={i}>{props.flow[nodeId].data?.text}</li>
))}
</ul>
</Box>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Radio from "@mui/material/Radio";
import React from "react";

export interface Props {
id: string;
id?: string;
title: string;
onChange: FormControlLabelProps["onChange"];
variant?: "default" | "compact";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import Typography from "@mui/material/Typography";
import React, { useLayoutEffect, useRef, useState } from "react";

export interface Props {
id: string;
id?: string;
title: string;
description?: string;
responseKey?: string | number;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ const Node: React.FC<any> = (props) => {
}
};

const getSetValueText = ({ operation, fn, val }: Store.Node["data"]) => {
const getSetValueText = ({ operation, fn, val }: Store.Node["data"] = {}) => {
switch (operation) {
case "append":
return `Append ${val} to ${fn}`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const DISPLAY_DATA: Partial<ComponentMap> = {
displayKey: "Option (data)",
getTitle: ({ item }) => {
const parentNode = useStore.getState().flow[item.parentId];
return parentNode.data.text;
return parentNode.data?.text;
},
getHeadline: ({ item, key }) => get(item, key)?.toString(),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const HeaderRoot = styled(Box)(({ theme }) => ({
}));

const InternalPortalHeader: React.FC<{ portalId: string }> = ({ portalId }) => {
const portalName = useStore((state) => state.flow)[portalId].data.text;
const portalName = useStore((state) => state.flow)[portalId].data?.text;
const Icon = ICONS[ComponentType.InternalPortal];

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
* Generate meaningful title for content analytic log
*/
export function getContentTitle(node: Store.Node): string {
const dom = new DOMParser().parseFromString(node.data.content, "text/html");
const dom = new DOMParser().parseFromString(node.data?.content, "text/html");
const h1 = dom.body.getElementsByTagName("h1")[0]?.textContent;
const text = h1 || dom.body.textContent;
if (!text) return `Content: ${node.id}`;
Expand Down
11 changes: 7 additions & 4 deletions editor.planx.uk/src/pages/FlowEditor/lib/store/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,13 +468,15 @@ export const previewStore: StateCreator<
passportValues = [passportValues];

passportValues = (passportValues || []).filter((pv: any) =>
sortedResponses.some((r) => pv.startsWith(r.data.val)),
sortedResponses.some((r) => pv.startsWith(r.data?.val)),
);

if (passportValues.length > 0) {
responsesThatCanBeAutoAnswered = (sortedResponses || []).filter(
(r) => {
const responseValues = String(r.data.val).split(",").sort();
const responseValues = String(r.data?.val)
.split(",")
.sort();
return String(responseValues) === String(passportValues);
},
);
Expand All @@ -483,7 +485,9 @@ export const previewStore: StateCreator<
responsesThatCanBeAutoAnswered = (
sortedResponses || []
).filter((r) => {
const responseValues = String(r.data.val).split(",").sort();
const responseValues = String(r.data?.val)
.split(",")
.sort();

for (const responseValue of responseValues) {
return passportValues.some((passportValue: any) =>
Expand Down Expand Up @@ -594,7 +598,6 @@ export const previewStore: StateCreator<
// Temporarily always returns false until upcomingCardIds is optimised
// OSL Slack explanation: https://bit.ly/3x38IRY
return false;

},

restore: false,
Expand Down

0 comments on commit 0a1cbc6

Please sign in to comment.