Skip to content
This repository has been archived by the owner on Mar 11, 2024. It is now read-only.

Commit

Permalink
refactor(client): Adds TS fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
eluciano11 committed Dec 21, 2023
1 parent 47c68d3 commit 60765e0
Show file tree
Hide file tree
Showing 13 changed files with 89 additions and 78 deletions.
8 changes: 6 additions & 2 deletions src/components/inscribete/SpecialVoters/Tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ const tabsState = {
},
}

const SpecialVotersTabsMachine = createMachine({
type SpecialVotersTabsEvent =
| { type: "EARLY_VOTER_TOGGLED" }
| { type: "ABSENTEE_VOTER_TOGGLED" }

const SpecialVotersTabsMachine = createMachine<{}, SpecialVotersTabsEvent>({
id: "special-voters-mobile",
initial: "earlyVoter",
states: tabsState,
Expand Down Expand Up @@ -67,7 +71,7 @@ export default function Tabs() {
</Tab>
</div>
<TabContent
key={state.value}
key={title}
title={t(title)}
summary={t(voter.summary)}
deadline={t(voter.deadline)}
Expand Down
30 changes: 0 additions & 30 deletions src/hooks/useMachineWithComponent.tsx

This file was deleted.

10 changes: 6 additions & 4 deletions src/packages/practica/components/Practicing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import BallotContainer from "./ballot-container"
interface PracticingProps {
state: any
send: any
handleSubmit: any
handleSubmit: VoidFunction
}

export const Practicing = ({ state, send, handleSubmit }: PracticingProps) => {
Expand All @@ -19,11 +19,13 @@ export const Practicing = ({ state, send, handleSubmit }: PracticingProps) => {
state,
state.value,
state.context.votes,
state.context.ballots.estatal,
state.context.ballots.legislativa,
state.context.ballots.municipal,
state.context.ballots?.estatal,
state.context.ballots?.legislativa,
state.context.ballots?.municipal,
])

if (state.context.ballots == null) return

return (
<div>
<ColumnHighlightProvider>
Expand Down
4 changes: 1 addition & 3 deletions src/packages/practica/components/ballot-status.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { ReactNode, useState } from "react"

import { ResultStatus } from "../../../ballot-validator/types"
import Arrows from "../../../components/arrows"

type BallotStatusType = {
children: ReactNode
status: ResultStatus | null
}

export default function BallotStatus({ children, status }: BallotStatusType) {
export default function BallotStatus({ children }: BallotStatusType) {
const [showFullscreen, setShowFullscreen] = useState(false)

if (showFullscreen) {
Expand Down
11 changes: 7 additions & 4 deletions src/packages/practica/components/practice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
} from "../services/ballot-configs"
// import useBallotValidation from "../hooks/use-ballot-validation"
import useVotesTransform from "../hooks/use-votes-transform"
import { PracticeMachine } from "../machines/practice"
import { BallotSelectionEvent, PracticeMachine } from "../machines/practice"
import useVotesCount from "../hooks/use-votes-count"
import { getExplicitlySelectedVotes, Vote } from "../services/vote-service"
import BallotFinderPicker from "./ballot-finder-picker"
Expand Down Expand Up @@ -194,7 +194,10 @@ export default function Practice({
}
}, [state.value])

const selectBallot = (selectedBallot: string, eventData: any) => {
const selectBallot = (
selectedBallot: BallotSelectionEvent["type"],
eventData: any
) => {
setSidebarIsVisible(false)
// setBallotStatus(null)
setVotesCount(null)
Expand Down Expand Up @@ -243,7 +246,7 @@ export default function Practice({
handleSubmit(
state.context.votes,
BallotType.municipality,
state.context.ballots.municipal
state.context.ballots?.municipal
),
}
}, [
Expand Down Expand Up @@ -391,7 +394,7 @@ export default function Practice({
pauseOnHover
/>
{votesCount && state.matches("practicing") && (
<BallotStatus status={null}>
<BallotStatus>
{ballotType === BallotType.state ? (
<ResultsState
votesCount={votesCount as StateVotesCount}
Expand Down
17 changes: 11 additions & 6 deletions src/packages/practica/hooks/use-error-messages.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import { useState } from "react"
import { toast } from "react-toastify"
import { useTranslation } from "react-i18next"
import { State } from "xstate"

import coordinatesToSections from "../services/coordinates-to-sections"
import BallotValidator from "../../../ballot-validator/index"

import useDeepCompareEffect from "./use-deep-compare-effect"
import { BallotType } from "../../../ballot-validator/types"
import { toFriendlyErrorMessages } from "../../../ballot-validator/helpers/messages"
import { MunicipalBallotConfig } from "../services/ballot-configs"
import { getExplicitlySelectedVotes } from "../services/vote-service"
import { PracticeContext } from "../services/types"
import { PracticeEvent } from "../machines/practice"

export default function useToast(state, dependencies: Array<any>) {
export default function useToast(
state: State<PracticeContext, PracticeEvent>,
dependencies: Array<any>
) {
const [isPristine, setIsPristine] = useState(true)
const { t } = useTranslation()

Expand All @@ -21,13 +26,13 @@ export default function useToast(state, dependencies: Array<any>) {

if (state.context.ballotType === BallotType.state) {
ballotType = BallotType.state
ballot = state.context.ballots.estatal
ballot = state.context.ballots?.estatal
} else if (state.context.ballotType === BallotType.legislative) {
ballotType = BallotType.legislative
ballot = state.context.ballots.legislativa
ballot = state.context.ballots?.legislativa
} else if (state.context.ballotType === BallotType.municipality) {
ballotType = BallotType.municipality
ballot = state.context.ballots.municipal
ballot = state.context.ballots?.municipal
}

if (!ballotType) {
Expand All @@ -49,7 +54,7 @@ export default function useToast(state, dependencies: Array<any>) {

toast.dismiss()

toFriendlyErrorMessages(validationResult)?.map(messageId => {
toFriendlyErrorMessages(validationResult)?.map((messageId) => {
if (
messageId.includes("MunicipalLegislatorDynamicSelectionRule") &&
ballotType === BallotType.municipality
Expand Down
6 changes: 2 additions & 4 deletions src/packages/practica/hooks/use-votes-transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,8 @@ function getBallot(state) {
}

export default function useVotesTransform(votes: Vote[], state) {
const [
transformedVotes,
setTransformedVotes,
] = useState<TransformedVotes | null>(null)
const [transformedVotes, setTransformedVotes] =
useState<TransformedVotes | null>(null)

useDeepCompareEffect<VotesCoordinates[]>(() => {
const res = getBallot(state)
Expand Down
33 changes: 24 additions & 9 deletions src/packages/practica/machines/practice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@ type ControlEvent =
| { type: "ENTER_VOTING_CENTER" }
| { type: "START_PRACTICE" }

type SelectionEvent =
export type BallotSelectionEvent =
| { type: "SELECTED_GOVERNMENTAL"; ballotType: BallotType }
| { type: "SELECTED_LEGISLATIVE"; ballotType: BallotType }
| { type: "SELECTED_MUNICIPAL"; ballotType: BallotType }
| { type: "BALLOT_SELECTION"; ballotType: BallotType }

export type SelectionEvent =
| { type: "SELECTED_VOTER_ID" }
| { type: "SELECTED_PRECINT" }
| { type: "SELECTED_GOVERNMENTAL" }
| { type: "SELECTED_LEGISLATIVE" }
| { type: "SELECTED_MUNICIPAL" }
| { type: "BALLOT_SELECTION"; ballotType: BallotType }

type DataEntryEvent =
| { type: "ADDED_VOTER_ID"; userInput: string }
Expand All @@ -38,11 +40,20 @@ type FetchBallotsEvent =
data: { ballots: BallotConfigs; ballotPaths: BallotsResponse }
}

type PracticeEvent =
type FindingVotingCenterInfoEvent =
| { type: "FINDING_VOTING_CENTER_INFO" }
| {
type: "done.invoke.findingVotingCenterInfo"
data: { ballotType: BallotType }
}

export type PracticeEvent =
| ControlEvent
| BallotSelectionEvent
| SelectionEvent
| DataEntryEvent
| FetchBallotsEvent
| FindingVotingCenterInfoEvent

export const PracticeMachine = createMachine<PracticeContext, PracticeEvent>(
{
Expand Down Expand Up @@ -129,6 +140,7 @@ export const PracticeMachine = createMachine<PracticeContext, PracticeEvent>(
},
},
fetchBallots: {
// @ts-ignore
invoke: {
id: "fetchBallots",
src: BallotService.fetchBallots,
Expand Down Expand Up @@ -164,6 +176,7 @@ export const PracticeMachine = createMachine<PracticeContext, PracticeEvent>(
},
},
findingVotingCenterInfo: {
// @ts-ignore
invoke: {
id: "findingVotingCenterInfo",
src: BallotService.fetchBallots,
Expand Down Expand Up @@ -225,9 +238,11 @@ export const PracticeMachine = createMachine<PracticeContext, PracticeEvent>(
},
{
actions: {
saveActiveBallotType: assign((_, { ballotType }) => ({
ballotType,
})),
saveActiveBallotType: assign(
(_, { ballotType }: BallotSelectionEvent) => ({
ballotType,
})
),
},
}
)
15 changes: 15 additions & 0 deletions src/packages/practica/services/ballot-configs/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,18 @@ export const ValidMarkLimits = {
[ElectivePosition.atLargeSenator]: 1,
},
}

export function getElectivePositionLimit(
ballotType: BallotType,
position: ElectivePosition
) {
if (!(ballotType in ValidMarkLimits)) throw new Error("Ballot type not found")

const limitsByBallotType = ValidMarkLimits[ballotType]

if (!(position in limitsByBallotType))
throw new Error("Position not found in ballot.")

// @ts-ignore
return limitsByBallotType[position]
}
5 changes: 3 additions & 2 deletions src/packages/practica/services/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ interface QueryParams {

export async function http<T>(request: RequestInfo): Promise<HttpResponse<T>> {
const response: HttpResponse<T> = await fetch(request)
response.parsedBody = await (response.text ? response.json() : null)

response.parsedBody = await response.json()

if (!response.ok) {
throw new Error("Bad response from server")
Expand All @@ -36,7 +37,7 @@ export async function post<T>(

const encodeQueryParams = (params: QueryParams) =>
Object.keys(params)
.map(k => encodeURIComponent(k) + "=" + encodeURIComponent(params[k]))
.map((k) => encodeURIComponent(k) + "=" + encodeURIComponent(params[k]))
.join("&")

export const createService = (baseUrl: string, options?: RequestInit) => ({
Expand Down
8 changes: 3 additions & 5 deletions src/packages/practica/strategies/mixed-vote-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
MunicipalBallotConfig,
} from "../services/ballot-configs"
import { Candidate } from "../services/ballot-configs/base"
import { ValidMarkLimits } from "../services/ballot-configs/constants"
import { getElectivePositionLimit } from "../services/ballot-configs/constants"
import { ElectivePosition } from "../services/ballot-configs/types"
import {
getColumnForParty,
Expand All @@ -24,7 +24,6 @@ export class MixedVoteStrategy implements VoteUpdateInterface {
Selection.selected,
intendedVote.candidate
)
const validMarkLimitsOnBallot = ValidMarkLimits[intendedVote.ballotType]

const electivePosition = getElectivePositionForVote(
vote.position,
Expand Down Expand Up @@ -62,7 +61,7 @@ export class MixedVoteStrategy implements VoteUpdateInterface {
const voteLimit =
electivePosition === ElectivePosition.municipalLegislators
? (ballot as MunicipalBallotConfig).amountOfMunicipalLegislators
: validMarkLimitsOnBallot[electivePosition]
: getElectivePositionLimit(intendedVote.ballotType, electivePosition)

// Get the section of the vote to determine how we should were we should subtract an implicit vote
if (totalVotesForPosition > voteLimit) {
Expand Down Expand Up @@ -96,7 +95,6 @@ export class MixedVoteStrategy implements VoteUpdateInterface {

// Go through every elective position and make sure it has an explict vote for the position or an implicit vote.
const ballot = intendedVote.ballot as BallotConfigs
const validMarkLimitsOnBallot = ValidMarkLimits[intendedVote.ballotType]
const electivePosition = getElectivePositionForVote(
intendedVote.position,
intendedVote.ballotType
Expand All @@ -117,7 +115,7 @@ export class MixedVoteStrategy implements VoteUpdateInterface {
const voteLimit =
electivePosition === ElectivePosition.municipalLegislators
? (ballot as MunicipalBallotConfig).amountOfMunicipalLegislators
: validMarkLimitsOnBallot[electivePosition]
: getElectivePositionLimit(intendedVote.ballotType, electivePosition)

// Add an implicit vote when it's removed.
if (explicitVotesForPosition.length < voteLimit) {
Expand Down
Loading

0 comments on commit 60765e0

Please sign in to comment.