mon-entreprise/source/engine/react.tsx

54 lines
1.3 KiB
TypeScript
Raw Normal View History

import Value from 'Components/Value'
import React, { createContext, useContext, useMemo } from 'react'
2020-04-05 21:27:31 +00:00
import rules, { DottedName } from 'Rules'
import Engine from '.'
export const EngineContext = createContext<{
engine: Engine<DottedName> | null
2020-03-12 13:55:32 +00:00
error: string | null
2020-03-26 15:03:19 +00:00
}>({ engine: new Engine({ rules }), error: null })
type InputProps = {
rules?: any
situation?: any
children: React.ReactNode
}
2020-03-26 15:03:19 +00:00
export function Provider({ rules, situation, children }: InputProps) {
const [engine, error] = useMemo(() => {
2020-03-12 13:55:32 +00:00
try {
2020-03-26 15:03:19 +00:00
return [new Engine({ rules }), null]
2020-03-12 13:55:32 +00:00
} catch (err) {
return [null, (err?.message ?? err.toString()) as string]
2020-03-12 13:55:32 +00:00
}
2020-03-26 15:03:19 +00:00
}, [rules])
2020-03-12 13:55:32 +00:00
if (engine !== null && !Object.is(situation, engine.situation)) {
engine.setSituation(situation)
}
return (
2020-03-12 13:55:32 +00:00
<EngineContext.Provider value={{ engine, error }}>
{children}
</EngineContext.Provider>
)
}
export function useEvaluation(expression: string) {
2020-03-12 13:55:32 +00:00
const { engine } = useContext(EngineContext)
return engine === null ? null : engine.evaluate(expression)
}
export function useError() {
return useContext(EngineContext).error
}
export function Evaluation({ expression }) {
const value = useEvaluation(expression)
2020-03-12 13:55:32 +00:00
return value === null ? null : <Value {...value} />
}
export default {
Provider,
useEvaluation,
2020-03-12 13:55:32 +00:00
useError,
Evaluation
}