Sync getRule and getParsedRules

engine-in-web-worker
Jérémy Rialland 2023-09-07 15:00:51 +02:00
parent 9355dca142
commit 529158bbb9
14 changed files with 126 additions and 149 deletions

View File

@ -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 (
<div>
@ -190,7 +194,7 @@ const TestWorkerEngine = () => {
)}
</p>
{/* <p>workerEngineCopy: {JSON.stringify(workerEngineCopy?.engineId)}</p>
<p>workerEngineCopy: {JSON.stringify(workerEngineCopy?.engineId)}</p>
<p>
dateCopy title:{' '}
@ -217,7 +221,7 @@ const TestWorkerEngine = () => {
? resultLazySmicCopy
: resultLazySmicCopy?.nodeValue
)}
</p> */}
</p>
</div>
)
}
@ -378,12 +382,10 @@ const App = () => {
<Route
path={relativeSitePaths.documentation.index + '/*'}
element={
<SuspensePromise isSSR={import.meta.env.SSR}>
<Documentation
documentationPath={documentationPath}
engine={workerEngine}
/>
</SuspensePromise>
<Documentation
documentationPath={documentationPath}
engine={workerEngine}
/>
}
/>
<Route

View File

@ -1,4 +1,4 @@
import { useAsyncGetRule, useWorkerEngine } from '@publicodes/worker-react'
import { useWorkerEngine } from '@publicodes/worker-react'
import { DottedName } from 'modele-social'
import { PublicodesExpression, serializeEvaluation } from 'publicodes'
import { useCallback } from 'react'
@ -156,8 +156,8 @@ function useAdjustProportions(CADottedName: DottedName) {
function ActivitéMixte() {
const dispatch = useDispatch()
const situation = useSelector(situationSelector)
const rule = useAsyncGetRule('entreprise . activités . revenus mixtes')
const workerEngine = useWorkerEngine()
const rule = workerEngine.getRule('entreprise . activités . revenus mixtes')
const defaultChecked =
usePromise(
() =>

View File

@ -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<Names extends string>({
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

View File

@ -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
}

View File

@ -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(

View File

@ -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<RuleNode<DottedName>>
)
),
@ -100,7 +98,7 @@ export default function AnswerList({ onClose, children }: AnswerListProps) {
] as Array<DottedName>
).filter(isCompanyDottedName)
)
).map((dottedName) => workerEngine.asyncGetRule(dottedName))
).map((dottedName) => workerEngine.getRule(dottedName))
),
[answeredAndPassedQuestions, companySituation, situation, workerEngine],
[] as RuleNode<DottedName>[]
@ -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) => {

View File

@ -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<HTMLFormElement>(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),

View File

@ -25,11 +25,7 @@ export function ExplicableRule<Names extends DottedName>({
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) {

View File

@ -19,10 +19,10 @@ export function MultipleChoicesInput<Names extends string = DottedName>(
) {
const { engineId, dottedName, onChange } = props
const workerEngine = useWorkerEngine()
const choices = usePromise(
() => getMultiplePossibilitiesOptions(workerEngine, engineId, dottedName),
[dottedName, engineId, workerEngine],
[] as RuleNode<DottedName>[]
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<Name>,
dottedName: DottedName
): Promise<RuleNode<DottedName>[]> {
): RuleNode<DottedName>[] {
// 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<DottedName>
)
}

View File

@ -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<Choice> => {
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']
}

View File

@ -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

View File

@ -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

View File

@ -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)
},

View File

@ -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
}