From 529158bbb9da4b1b907827f9e193d3594f1d8a9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Rialland?= Date: Thu, 7 Sep 2023 15:00:51 +0200 Subject: [PATCH] Sync getRule and getParsedRules --- site/source/components/App.tsx | 124 +++++++++--------- .../ChiffreAffairesActivitéMixte.tsx | 4 +- site/source/components/EngineValue.tsx | 6 +- site/source/components/RuleLink.tsx | 25 ++-- .../components/Simulation/SimulationGoal.tsx | 5 +- .../components/conversation/AnswerList.tsx | 23 ++-- .../components/conversation/Conversation.tsx | 9 +- .../components/conversation/Explicable.tsx | 6 +- .../conversation/MulipleChoicesInput.tsx | 29 ++-- .../components/conversation/RuleInput.tsx | 15 +-- .../InstitutionsPartenaires.tsx | 7 +- .../utils/useSearchParamsSimulationSharing.ts | 13 +- site/source/hooks/useNextQuestion.tsx | 4 +- .../store/selectors/simulationSelectors.ts | 5 +- 14 files changed, 126 insertions(+), 149 deletions(-) diff --git a/site/source/components/App.tsx b/site/source/components/App.tsx index 8a1ef953f..2bc8412d4 100644 --- a/site/source/components/App.tsx +++ b/site/source/components/App.tsx @@ -1,7 +1,5 @@ import { SuspensePromise, - useAsyncGetRule, - useAsyncParsedRules, useAsyncShallowCopy, useLazyPromise, usePromise, @@ -61,10 +59,13 @@ const TestWorkerEngine = () => { { defaultValue: 'loading...' } ) - const date = useAsyncGetRule('date', { defaultValue: 'loading...' }) - const SMIC = useAsyncGetRule('SMIC', { defaultValue: 'loading...' }) + // const date = useAsyncGetRule('date', { defaultValue: 'loading...' }) + // const SMIC = useAsyncGetRule('SMIC', { defaultValue: 'loading...' }) + const date = workerEngine.getRule('date') + const SMIC = workerEngine.getRule('SMIC') - const parsedRules = useAsyncParsedRules() + // const parsedRules = useAsyncParsedRules() + const parsedRules = workerEngine.getParsedRules() const resultSmic = usePromise( () => workerEngine.asyncEvaluate('SMIC'), @@ -87,17 +88,17 @@ const TestWorkerEngine = () => { })() }, [triggerLazySmic, workerEngine.isWorkerReady]) - // const workerEngineCopy = useAsyncShallowCopy(workerEngine) - // // // const workerEngineCopy = workerEngine - // console.log('=========>', workerEngine, workerEngineCopy) + const workerEngineCopy = useAsyncShallowCopy(workerEngine) + // // const workerEngineCopy = workerEngine + console.log('=========>', workerEngine, workerEngineCopy) - // const [, triggerCopy] = useLazyPromise(async () => { - // console.log('+++++++++>', workerEngineCopy) + const [, triggerCopy] = useLazyPromise(async () => { + console.log('+++++++++>', workerEngineCopy) - // await workerEngineCopy?.asyncSetSituation({ - // SMIC: '2000€/mois', - // }) - // }, [workerEngineCopy]) + await workerEngineCopy?.asyncSetSituation({ + SMIC: '2000€/mois', + }) + }, [workerEngineCopy]) // const dateCopy = useAsyncGetRule('date', { // defaultValue: 'loading...', @@ -108,51 +109,54 @@ const TestWorkerEngine = () => { // workerEngine: workerEngineCopy, // }) - // const resultSmicCopy = usePromise( - // async () => - // !workerEngineCopy - // ? 'still loading...' - // : workerEngineCopy.asyncEvaluate('SMIC'), - // [workerEngineCopy], - // 'loading...' - // ) + const dateCopy = workerEngineCopy?.getRule('date') + const parsedRulesCopy = workerEngineCopy?.getParsedRules() - // const [resultLazySmicCopy, triggerLazySmicCopy] = useLazyPromise( - // async () => - // !workerEngineCopy - // ? 'still loading...' - // : workerEngineCopy.asyncEvaluate('SMIC'), - // [workerEngineCopy], - // 'wait 3sec...' - // ) + const resultSmicCopy = usePromise( + async () => + !workerEngineCopy + ? 'still loading...' + : workerEngineCopy.asyncEvaluate('SMIC'), + [workerEngineCopy], + 'loading...' + ) - // useEffect(() => { - // // console.log('useEffect') + const [resultLazySmicCopy, triggerLazySmicCopy] = useLazyPromise( + async () => + !workerEngineCopy + ? 'still loading...' + : workerEngineCopy.asyncEvaluate('SMIC'), + [workerEngineCopy], + 'wait 3sec...' + ) - // void (async () => { - // await workerEngine.isWorkerReady - // setTimeout(() => { - // void triggerLazySmicCopy() - // }, 3000) - // })() - // }, [triggerLazySmicCopy, workerEngine.isWorkerReady]) + useEffect(() => { + // console.log('useEffect') - // const { asyncSetSituation } = workerEngineCopy ?? {} - // usePromise(async () => { - // // console.log('**************>', workerEngineCopy, resultSmic) + void (async () => { + await workerEngine.isWorkerReady + setTimeout(() => { + void triggerLazySmicCopy() + }, 3000) + })() + }, [triggerLazySmicCopy, workerEngine.isWorkerReady]) - // if ( - // resultSmic && - // typeof resultSmic !== 'string' && - // typeof resultSmic.nodeValue === 'number' - // ) { - // // console.log('ooooooooooooooooooo', resultSmic) + const { asyncSetSituation } = workerEngineCopy ?? {} + usePromise(async () => { + // console.log('**************>', workerEngineCopy, resultSmic) - // await asyncSetSituation?.({ - // SMIC: resultSmic.nodeValue + '€/mois', - // }) - // } - // }, [asyncSetSituation, resultSmic]) + if ( + resultSmic && + typeof resultSmic !== 'string' && + typeof resultSmic.nodeValue === 'number' + ) { + // console.log('ooooooooooooooooooo', resultSmic) + + await asyncSetSituation?.({ + SMIC: resultSmic.nodeValue + '€/mois', + }) + } + }, [asyncSetSituation, resultSmic]) return (
@@ -190,7 +194,7 @@ const TestWorkerEngine = () => { )}

- {/*

workerEngineCopy: {JSON.stringify(workerEngineCopy?.engineId)}

+

workerEngineCopy: {JSON.stringify(workerEngineCopy?.engineId)}

dateCopy title:{' '} @@ -217,7 +221,7 @@ const TestWorkerEngine = () => { ? resultLazySmicCopy : resultLazySmicCopy?.nodeValue )} -

*/} +

) } @@ -378,12 +382,10 @@ const App = () => { - - + } /> diff --git a/site/source/components/EngineValue.tsx b/site/source/components/EngineValue.tsx index 6504adc05..300a7f196 100644 --- a/site/source/components/EngineValue.tsx +++ b/site/source/components/EngineValue.tsx @@ -1,4 +1,4 @@ -import { useAsyncParsedRules, useWorkerEngine } from '@publicodes/worker-react' +import { useWorkerEngine } from '@publicodes/worker-react' import { DottedName } from 'modele-social' import { ASTNode, @@ -45,9 +45,7 @@ export default function Value({ if (expression === null) { throw new TypeError('expression cannot be null') } - const parsedRules = useAsyncParsedRules({ - workerEngine, - }) + const parsedRules = workerEngine.getParsedRules() const isRule = typeof expression === 'string' && parsedRules && expression in parsedRules diff --git a/site/source/components/RuleLink.tsx b/site/source/components/RuleLink.tsx index 607cb1a6e..3ae394e4e 100644 --- a/site/source/components/RuleLink.tsx +++ b/site/source/components/RuleLink.tsx @@ -1,4 +1,4 @@ -import { usePromise, useWorkerEngine } from '@publicodes/worker-react' +import { useWorkerEngine } from '@publicodes/worker-react' import { DottedName } from 'modele-social' import { RuleLink as EngineRuleLink } from 'publicodes-react' import React from 'react' @@ -16,24 +16,17 @@ export default function RuleLink( ) { const { dottedName, documentationPath, children, ...linkProps } = props const { absoluteSitePaths } = useSitePaths() - const [loading, setLoading] = React.useState(true) - const [error, setError] = React.useState(false) + const workerEngine = useWorkerEngine() - usePromise(async () => { - setLoading(true) - setError(false) + let error = false + try { + workerEngine.getRule(dottedName) + } catch (err) { + error = true + } - try { - const rule = await workerEngine.asyncGetRule(dottedName) - } catch (error) { - setError(true) - } - - setLoading(false) - }, [dottedName, workerEngine]) - - if (loading || error) { + if (error) { return null } diff --git a/site/source/components/Simulation/SimulationGoal.tsx b/site/source/components/Simulation/SimulationGoal.tsx index c56476ab5..0edc0f6bb 100644 --- a/site/source/components/Simulation/SimulationGoal.tsx +++ b/site/source/components/Simulation/SimulationGoal.tsx @@ -1,4 +1,4 @@ -import { useAsyncGetRule, useWorkerEngine } from '@publicodes/worker-react' +import { useWorkerEngine } from '@publicodes/worker-react' import { DottedName } from 'modele-social' import { formatValue, PublicodesExpression } from 'publicodes' import React, { useCallback, useState } from 'react' @@ -60,7 +60,8 @@ export function SimulationGoal({ }), [workerEngine, dottedName, round, isTypeBoolean, currentUnit] ) - const rule = useAsyncGetRule(dottedName) + // const rule = useAsyncGetRule(dottedName) + const rule = workerEngine.getRule(dottedName) const initialRender = useInitialRender() const [isFocused, setFocused] = useState(false) const onChange = useCallback( diff --git a/site/source/components/conversation/AnswerList.tsx b/site/source/components/conversation/AnswerList.tsx index d6f3d180c..b15d3a8b7 100644 --- a/site/source/components/conversation/AnswerList.tsx +++ b/site/source/components/conversation/AnswerList.tsx @@ -55,9 +55,7 @@ export default function AnswerList({ onClose, children }: AnswerListProps) { !passedQuestions.some((passed) => answered === passed) ) .concat(passedQuestions) - .map( - async (dottedName) => await workerEngine.asyncGetRule(dottedName) - ) + .map((dottedName) => workerEngine.getRule(dottedName)) ) ).filter((rule) => rule.rawNode.question !== undefined), [passedQuestions, situation, workerEngine], @@ -70,7 +68,7 @@ export default function AnswerList({ onClose, children }: AnswerListProps) { nextQuestions.map( async (dottedName) => workerEngine.asyncEvaluate( - await workerEngine.asyncGetRule(dottedName) + workerEngine.getRule(dottedName) ) as Promise> ) ), @@ -100,7 +98,7 @@ export default function AnswerList({ onClose, children }: AnswerListProps) { ] as Array ).filter(isCompanyDottedName) ) - ).map((dottedName) => workerEngine.asyncGetRule(dottedName)) + ).map((dottedName) => workerEngine.getRule(dottedName)) ), [answeredAndPassedQuestions, companySituation, situation, workerEngine], [] as RuleNode[] @@ -300,16 +298,11 @@ function AnswerElement(rule: RuleNode) { const dispatch = useDispatch() const workerEngine = useWorkerEngine() const parentDottedName = utils.ruleParent(rule.dottedName) as DottedName - const questionDottedName = usePromise( - async () => - rule.rawNode.question - ? (rule.dottedName as DottedName) - : parentDottedName && - (await workerEngine.asyncGetRule(parentDottedName)).rawNode.API - ? parentDottedName - : undefined, - [parentDottedName, rule.dottedName, rule.rawNode.question, workerEngine] - ) + const questionDottedName = rule.rawNode.question + ? (rule.dottedName as DottedName) + : parentDottedName && workerEngine.getRule(parentDottedName).rawNode.API + ? parentDottedName + : undefined const handleChange = useCallback( (value: PublicodesExpression | undefined) => { diff --git a/site/source/components/conversation/Conversation.tsx b/site/source/components/conversation/Conversation.tsx index b62853de9..f4942fdc2 100644 --- a/site/source/components/conversation/Conversation.tsx +++ b/site/source/components/conversation/Conversation.tsx @@ -1,8 +1,4 @@ -import { - useAsyncGetRule, - useWorkerEngine, - WorkerEngine, -} from '@publicodes/worker-react' +import { useWorkerEngine, WorkerEngine } from '@publicodes/worker-react' import { DottedName } from 'modele-social' import Engine, { PublicodesExpression, RuleNode } from 'publicodes' import React, { useCallback, useEffect, useState } from 'react' @@ -92,7 +88,8 @@ export default function Conversation({ const formRef = React.useRef(null) const workerEngine = useWorkerEngine() - const rule = useAsyncGetRule(currentQuestion) + // const rule = useAsyncGetRule(currentQuestion) + const rule = workerEngine.getRule(currentQuestion) const question = usePromise( async () => rule && evaluateQuestion(workerEngine, rule), diff --git a/site/source/components/conversation/Explicable.tsx b/site/source/components/conversation/Explicable.tsx index 3568e8d73..7cdfda7de 100644 --- a/site/source/components/conversation/Explicable.tsx +++ b/site/source/components/conversation/Explicable.tsx @@ -25,11 +25,7 @@ export function ExplicableRule({ title?: string }) { const workerEngine = useWorkerEngine() - const rule = usePromise( - async () => - dottedName != null ? workerEngine.asyncGetRule(dottedName) : null, - [dottedName, workerEngine] - ) + const rule = dottedName != null ? workerEngine.getRule(dottedName) : null // Rien à expliquer ici, ce n'est pas une règle if (dottedName == null) { diff --git a/site/source/components/conversation/MulipleChoicesInput.tsx b/site/source/components/conversation/MulipleChoicesInput.tsx index 7151cd6dc..5d659e485 100644 --- a/site/source/components/conversation/MulipleChoicesInput.tsx +++ b/site/source/components/conversation/MulipleChoicesInput.tsx @@ -19,10 +19,10 @@ export function MultipleChoicesInput( ) { const { engineId, dottedName, onChange } = props const workerEngine = useWorkerEngine() - const choices = usePromise( - () => getMultiplePossibilitiesOptions(workerEngine, engineId, dottedName), - [dottedName, engineId, workerEngine], - [] as RuleNode[] + const choices = getMultiplePossibilitiesOptions( + workerEngine, + engineId, + dottedName ) const handleChange = (isSelected: boolean, dottedName: DottedName) => { @@ -93,27 +93,26 @@ function CheckBoxRule({ node, engineId, onChange }: CheckBoxRuleProps) { ) } -async function getMultiplePossibilitiesOptions( +function getMultiplePossibilitiesOptions( workerEngine: WorkerEngine, engineId: number, // engine: Engine, dottedName: DottedName -): Promise[]> { +): RuleNode[] { // return ( // (engine.getRule(dottedName) as RuleWithMultiplePossibilities).rawNode[ // 'plusieurs possibilités' // ] ?? [] // ).map((name) => engine.getRule(`${dottedName} . ${name}` as Name)) const posibilities = - ( - (await workerEngine.asyncGetRule( - dottedName - )) as RuleWithMultiplePossibilities - ).rawNode['plusieurs possibilités'] ?? [] + (workerEngine.getRule(dottedName) as RuleWithMultiplePossibilities).rawNode[ + 'plusieurs possibilités' + ] ?? [] - return await Promise.all( - posibilities.map((name) => - workerEngine.asyncGetRule(`${dottedName} . ${name}` as DottedName) - ) + return posibilities.map( + (name) => + workerEngine.getRule( + `${dottedName} . ${name}` as DottedName + ) as RuleNode ) } diff --git a/site/source/components/conversation/RuleInput.tsx b/site/source/components/conversation/RuleInput.tsx index 21cb5b66c..c39a9e72b 100644 --- a/site/source/components/conversation/RuleInput.tsx +++ b/site/source/components/conversation/RuleInput.tsx @@ -1,5 +1,5 @@ import { - useAsyncGetRule, + usePromise, useWorkerEngine, WorkerEngine, } from '@publicodes/worker-react' @@ -17,7 +17,6 @@ import React, { useEffect } from 'react' import NumberInput from '@/components/conversation/NumberInput' import SelectCommune from '@/components/conversation/select/SelectCommune' import { DateFieldProps } from '@/design-system/field/DateField' -import { usePromise } from '@/hooks/usePromise' import { getMeta, isNotNull } from '@/utils' import { Choice, MultipleAnswerInput, OuiNonInput } from './ChoicesInput' @@ -98,7 +97,8 @@ export default function RuleInput({ const workerEngine = useWorkerEngine() - const rule = useAsyncGetRule(dottedName) + // const rule = useAsyncGetRule(dottedName) + const rule = workerEngine.getRule(dottedName) // const evaluation = engineValue.evaluate({ valeur: dottedName, ...modifiers }) // async @@ -263,7 +263,7 @@ const getOnePossibilityOptions = async ( // engineId: number, path: DottedName ): Promise => { - const node = await workerEngine.asyncGetRule(path) + const node = workerEngine.getRule(path) // if (path === 'entreprise . activité . nature') debugger @@ -322,9 +322,6 @@ async function isMultiplePossibilities( // return !!(engine.getRule(dottedName) as RuleWithMultiplePossibilities) // .rawNode['plusieurs possibilités'] - return !!( - (await workerEngine.asyncGetRule( - dottedName - )) as RuleWithMultiplePossibilities - ).rawNode['plusieurs possibilités'] + return !!(workerEngine.getRule(dottedName) as RuleWithMultiplePossibilities) + .rawNode['plusieurs possibilités'] } diff --git a/site/source/components/simulationExplanation/InstitutionsPartenaires.tsx b/site/source/components/simulationExplanation/InstitutionsPartenaires.tsx index 6f10217dc..8d580ebcb 100644 --- a/site/source/components/simulationExplanation/InstitutionsPartenaires.tsx +++ b/site/source/components/simulationExplanation/InstitutionsPartenaires.tsx @@ -1,3 +1,4 @@ +import { useWorkerEngine } from '@publicodes/worker-react' import { DottedName } from 'modele-social' import { Trans } from 'react-i18next' import { useSelector } from 'react-redux' @@ -253,7 +254,11 @@ function CaisseRetraite({ role }: { role?: string }) { export function InstitutionsPartenairesArtisteAuteur() { const unit = useSelector(targetUnitSelector) - const descriptionIRCEC = useAsyncGetRule( + const workerEngine = useWorkerEngine() + // const descriptionIRCEC = useAsyncGetRule( + // 'artiste-auteur . cotisations . IRCEC' as DottedName + // )?.rawNode.description + const descriptionIRCEC = workerEngine.getRule( 'artiste-auteur . cotisations . IRCEC' as DottedName )?.rawNode.description diff --git a/site/source/components/utils/useSearchParamsSimulationSharing.ts b/site/source/components/utils/useSearchParamsSimulationSharing.ts index 3a9604fc5..42c8e83b9 100644 --- a/site/source/components/utils/useSearchParamsSimulationSharing.ts +++ b/site/source/components/utils/useSearchParamsSimulationSharing.ts @@ -1,8 +1,4 @@ -import { - useAsyncParsedRules, - useWorkerEngine, - WorkerEngine, -} from '@publicodes/worker-react' +import { useWorkerEngine, WorkerEngine } from '@publicodes/worker-react' import { DottedName } from 'modele-social' import { ParsedRules, serializeEvaluation } from 'publicodes' import { useEffect, useMemo, useState } from 'react' @@ -28,7 +24,9 @@ export default function useSearchParamsSimulationSharing() { const [searchParams, setSearchParams] = useSearchParams() const objectifs = useSelector(configObjectifsSelector) const dispatch = useDispatch() - const parsedRules = useAsyncParsedRules() + // const parsedRules = useAsyncParsedRules() + const workerEngine = useWorkerEngine() + const parsedRules = workerEngine.getParsedRules() const dottedNameParamName = useMemo( () => (parsedRules ? getRulesParamNames(parsedRules) : []), @@ -76,8 +74,9 @@ export default function useSearchParamsSimulationSharing() { export const useParamsFromSituation = () => { const situation = useSelector(situationSelector) const companySituation = useSelector(companySituationSelector) - const parsedRules = useAsyncParsedRules() + // const parsedRules = useAsyncParsedRules() const workerEngine = useWorkerEngine() + const parsedRules = workerEngine.getParsedRules() const ret = usePromise(() => { const dottedNameParamName = parsedRules diff --git a/site/source/hooks/useNextQuestion.tsx b/site/source/hooks/useNextQuestion.tsx index ad412e1ea..c863eba03 100644 --- a/site/source/hooks/useNextQuestion.tsx +++ b/site/source/hooks/useNextQuestion.tsx @@ -85,9 +85,7 @@ export const useNextQuestions = function ( answeredQuestions ) - const rules = await Promise.all( - next.map((question) => workerEngine.asyncGetRule(question)) - ) + const rules = next.map((question) => workerEngine.getRule(question)) return next.filter((_, i) => rules[i].rawNode.question !== undefined) }, diff --git a/site/source/store/selectors/simulationSelectors.ts b/site/source/store/selectors/simulationSelectors.ts index bde7b4d9e..2e5601b0c 100644 --- a/site/source/store/selectors/simulationSelectors.ts +++ b/site/source/store/selectors/simulationSelectors.ts @@ -95,10 +95,9 @@ async function treatAPIMissingVariables( return ( await Promise.all( (Object.entries(missingVariables) as [DottedName, number][]).map( - async ([name, value]) => { + ([name, value]) => { const parentName = utils.ruleParent(name) as DottedName - const rule = - parentName && (await workerEngine.asyncGetRule(parentName)) + const rule = parentName && workerEngine.getRule(parentName) return [name, value, parentName, rule.rawNode.API] as const }