From 46211638f5ee84233bd86e84b7a0021a83faea98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julien=20Valverd=C3=A9?= Date: Fri, 28 Mar 2025 21:19:17 +0100 Subject: [PATCH] Refactoring --- packages/reffuse/src/ReffuseContext.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/reffuse/src/ReffuseContext.ts b/packages/reffuse/src/ReffuseContext.ts index 95466a4..4470cfa 100644 --- a/packages/reffuse/src/ReffuseContext.ts +++ b/packages/reffuse/src/ReffuseContext.ts @@ -24,6 +24,7 @@ export type R = T extends ReffuseContext ? R : never export type ReactProvider = React.FC<{ readonly layer: Layer.Layer + readonly scope?: Scope.Scope readonly children?: React.ReactNode }> @@ -32,6 +33,11 @@ const makeProvider = (Context: React.Context>): ReactProvi const runtime = ReffuseRuntime.useRuntime() const runSync = React.useMemo(() => Runtime.runSync(runtime), [runtime]) + const makeScope = React.useMemo(() => props.scope + ? Scope.fork(props.scope, ExecutionStrategy.sequential) + : Scope.make(), + [props.scope]) + const makeContext = React.useCallback((scope: Scope.CloseableScope) => Effect.context().pipe( Effect.provide(props.layer), Effect.provideService(Scope.Scope, scope), @@ -39,7 +45,7 @@ const makeProvider = (Context: React.Context>): ReactProvi const [isInitialRun, initialScope, initialValue] = React.useMemo(() => Effect.Do.pipe( Effect.bind("isInitialRun", () => Ref.make(true)), - Effect.bind("scope", () => Scope.make()), + Effect.bind("scope", () => makeScope), Effect.bind("context", ({ scope }) => makeContext(scope)), Effect.map(({ isInitialRun, scope, context }) => [isInitialRun, scope, context] as const), runSync, @@ -56,7 +62,7 @@ const makeProvider = (Context: React.Context>): ReactProvi ), onFalse: () => Effect.Do.pipe( - Effect.bind("scope", () => Scope.make()), + Effect.bind("scope", () => makeScope), Effect.bind("context", ({ scope }) => makeContext(scope)), Effect.tap(({ context }) => Effect.sync(() => setValue(context)) @@ -68,7 +74,7 @@ const makeProvider = (Context: React.Context>): ReactProvi }), runSync, - ), [makeContext, runSync]) + ), [makeScope, makeContext, runSync]) return React.createElement(Context, { ...props, value }) }