Skip to content

Commit

Permalink
Compliqué la gestion des searchparams
Browse files Browse the repository at this point in the history
  • Loading branch information
laem committed Aug 7, 2023
1 parent 06468ae commit e7fefc5
Show file tree
Hide file tree
Showing 15 changed files with 321 additions and 306 deletions.
1 change: 1 addition & 0 deletions .env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
NEXT_PUBLIC_NODE_ENV=development
1 change: 1 addition & 0 deletions app/components/Congratulations.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
'use client'
import { useDispatch } from 'react-redux'
import tinygradient from 'tinygradient'
import { Dialog } from './GameOver'
Expand Down
5 changes: 3 additions & 2 deletions app/components/Simulation.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
'use client'
import Conversation, {
ConversationProps,
} from 'Components/conversation/Conversation'
import SearchButton from 'Components/SearchButton'
import * as animate from 'Components/ui/animate'
import React from 'react'
import AnswerList from './conversation/AnswerList'
import { syncSearchParams } from './utils/useSearchParamsSimulationSharing'
//TODO import { syncSearchParams } from './utils/useSearchParamsSimulationSharing'

type SimulationProps = {
explanations?: React.ReactNode
Expand All @@ -28,7 +29,7 @@ export default function Simulation({
const Animation = animate[animation]
//const situation = useSelector(situationSelector)
//const searchParams = useParamsFromSituation(situation)
syncSearchParams()
// TODO syncSearchParams()
return (
<>
<AnswerList />
Expand Down
34 changes: 0 additions & 34 deletions app/components/utils/Meta.tsx

This file was deleted.

27 changes: 22 additions & 5 deletions app/components/utils/useSearchParamsSimulationSharing.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
'use client'
import { batchUpdateSituation } from '@/app/actions'
import { useEngine } from 'Components/utils/EngineContext'
import { usePathname, useSearchParams } from 'next/navigation'
import { useRouter } from 'next/router'
import Engine, { ParsedRules, serializeEvaluation } from 'publicodes'
import { useEffect, useMemo, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useLocation } from 'react-router'
import { useSearchParams } from 'react-router-dom'
import { configSelector } from 'Selectors/simulationSelectors'
import { batchUpdateSituation } from '@/app/actions'
import {
RootState,
SimulationConfig,
Expand All @@ -19,7 +21,22 @@ type DottedName = string
type ParamName = DottedName | ShortName

export function syncSearchParams() {
const [searchParams, setSearchParams] = useSearchParams()
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()!

// Get a new searchParams string by merging the current
// searchParams with a provided key/value pair
const createQueryString = useCallback(
(name: string, value: string) => {
const params = new URLSearchParams(searchParams)
params.set(name, value)

return params.toString()
},
[searchParams]
)

const dispatch = useDispatch()
const situation = useSelector(situationSelector)
const situationSearchParams = useParamsFromSituation(situation)
Expand All @@ -37,7 +54,7 @@ export function syncSearchParams() {
dispatch(batchUpdateSituation(newSituation as Situation))
}, [])
useEffect(() => {
setSearchParams(situationSearchParams, { replace: true })
router.push(pathname + '?' + situationSearchParams.toString())
}, [situationSearchParams.toString()])
}

Expand Down
5 changes: 4 additions & 1 deletion app/providers/Providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@
import { useServerInsertedHTML } from 'next/navigation'
import { PropsWithChildren } from 'react'
import ReduxProvider from './ReduxProvider'
import RulesProvider from './RulesProvider'

type P = PropsWithChildren

export default function Providers({ children }: P) {
return (
// you can have multiple client side providers wrapped, in this case I am also using NextUIProvider
<>
<ReduxProvider>{children}</ReduxProvider>
<ReduxProvider>
<RulesProvider>{children}</RulesProvider>
</ReduxProvider>
</>
)
}
16 changes: 13 additions & 3 deletions app/providers/ReduxProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
'use client'

import reducers from '@/app/reducers'
import { PropsWithChildren } from 'react'
import { PropsWithChildren, useMemo } from 'react'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import { applyMiddleware, createStore, compose } from 'redux'
import thunk from 'redux-thunk'

const composeEnhancers =
(typeof window !== 'undefined' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||
compose

export default function ReduxProvider({ children }: PropsWithChildren) {
const store = createStore(reducers)
const store = useMemo(() => {
const storeEnhancer = applyMiddleware(thunk)
return createStore(reducers, {}, composeEnhancers(storeEnhancer))
}, [])

return <Provider store={store}>{children}</Provider>
}
20 changes: 12 additions & 8 deletions old/source/RulesProvider.js → app/providers/RulesProvider.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
'use client'

import {
EngineProvider,
SituationProvider,
engineOptions,
} from 'Components/utils/EngineContext'

import {
configSituationSelector,
situationSelector,
Expand All @@ -12,9 +15,10 @@ import Engine from 'publicodes'
import React, { useEffect, useMemo } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import zeros from './zeroDefaults.yaml'
import { useLocation } from 'react-router'

import transformRules from './transformRules'
import { useParams, usePathname } from 'next/navigation'
import { useSearchParams } from 'react-router-dom'

// This is a difficult task : categories must equal to zero, in order to not make the test fail without having answered to a non-zero per default category
// but some categories are conditionned by one variable, like the housing which is divided by the number of inhabitants.
Expand Down Expand Up @@ -62,15 +66,15 @@ export default ({ children }) => {

const setRules = (rules) => dispatch({ type: 'SET_RULES', rules })

const urlParams = new URLSearchParams(window.location.search)
const location = useLocation()
const urlParams = new URLSearchParams(useParams())
const pathname = usePathname()

const branch = urlParams.get('branch')
const pullRequestNumber = urlParams.get('PR')

useEffect(() => {
const rulesDomain = ['/simulateur/bilan', '/instructions', '/fin'].find(
(url) => location.pathname.indexOf(url) === 0
(url) => pathname.indexOf(url) === 0
)
? 'data.nosgestesclimat.fr/co2-model.FR-lang.fr.json'
: 'futureco-data.netlify.app/co2.json'
Expand All @@ -87,7 +91,7 @@ export default ({ children }) => {
const dataBranch = branch || pullRequestNumber
if (
false && // To be reactivated when in a dev branch for the final work on this test section on the site, that is based on nosgestesclimat's model
NODE_ENV === 'development' &&
process.env.NODE_ENV === 'development' &&
!dataBranch &&
rulesDomain.includes('ecolab-data')
) {
Expand Down Expand Up @@ -129,13 +133,13 @@ export default ({ children }) => {
setRules(setDefaultsToZero(rules))
removeLoader()
} else if (
NODE_ENV === 'development' &&
process.env.NODE_ENV === 'development' &&
!dataBranch &&
rulesDomain.includes('futureco-data')
) {
// Rules are stored in nested yaml files
const req = require.context(
'../../futureco-data/data/',
'../../../futureco-data/data/',
true,
/\.(yaml)$/
)
Expand Down Expand Up @@ -170,7 +174,7 @@ export default ({ children }) => {
removeLoader()
})
}
}, [location.pathname, branch, pullRequestNumber])
}, [pathname, branch, pullRequestNumber])

if (!rules) return null
return <EngineWrapper rules={rules}>{children}</EngineWrapper>
Expand Down
File renamed without changes.
File renamed without changes.
46 changes: 46 additions & 0 deletions app/simulateur/[...dottedName]/Simulateur.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
'use client'

import { setSimulationConfig } from '@/app/actions'
import { questionEcoDimensions } from '@/app/components/questionEcoDimensions'
import { parentName } from 'Components/utils/publicodesUtils'
import { usePathname } from 'next/navigation'
import { compose, isEmpty, symmetricDifference } from 'ramda'
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import configBuilder from './configBuilder'
import SimulateurContent from './SimulateurContent'

const eqValues = compose(isEmpty, symmetricDifference)

export default ({ dottedName }) => {
const dispatch = useDispatch()
const pathname = usePathname()

const rules = useSelector((state) => state.rules)

if (!rules) return 'Les règles ne sont pas chargées'
const decodedRule = rules[dottedName]

if (!decodedRule) return 'Règle non trouvée'
const objectifs =
decodedRule.exposé?.type === 'question éco'
? questionEcoDimensions.map(
(dimension) => parentName(dottedName) + ' . ' + dimension
)
: [dottedName]

const config = configBuilder(objectifs, dottedName),
configSet = useSelector((state) => state.simulation?.config)
const wrongConfig = !eqValues(config.objectifs, configSet?.objectifs || [])
useEffect(
() =>
wrongConfig
? dispatch(setSimulationConfig(config, pathname))
: () => null,
[]
)

if (!configSet || wrongConfig) return null

return <SimulateurContent objective={dottedName} />
}
Loading

0 comments on commit e7fefc5

Please sign in to comment.