Skip to content

Commit

Permalink
Support globally scoped lifecycle
Browse files Browse the repository at this point in the history
  • Loading branch information
loganvolkers authored Nov 23, 2023
1 parent 49dd7e6 commit a259729
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
8 changes: 7 additions & 1 deletion src/vanilla/injector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,12 @@ import type {
MoleculeOrInterface,
ScopeGetter,
} from "./molecule";
import { createScope } from "./scope";
import { createScoper } from "./scoper";
import type { BindingMap, Bindings, Injectable } from "./types";

const InternalOnlyGlobalScope = createScope(undefined);

type Deps = {
scopes: Set<AnyMoleculeScope>;
transitiveScopes: Set<AnyMoleculeScope>;
Expand Down Expand Up @@ -265,7 +268,9 @@ export function createInjector(
// `onUnmounted` can be used for default scopes
defaultTuple = scoper.leaseScope(defaultTuple, context.subscriptionId);
} else {
console.warn("Default subscription not leased!");
// TODO: Find a nice way to provide warnings only in dev mode
// so we don't put a bunch of junk in the console on production
// console.warn("Default subscription not leased!");
}

defaultScopeTuples.add(defaultTuple);
Expand Down Expand Up @@ -453,6 +458,7 @@ function runMolecule(
onMountImpl.push((fn: MountedCallback) => mountedCallbacks.add(fn));
useImpl.push(use);
let running = true;
trackingScopeGetter(InternalOnlyGlobalScope);
const value = m[GetterSymbol](trackingGetter, trackingScopeGetter);
running = false;
onMountImpl.pop();
Expand Down
22 changes: 12 additions & 10 deletions src/vanilla/lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,21 +280,23 @@ describe("Two scope dependencies", () => {
});

test("Can't use `mounted` hook in globally scoped molecule", () => {
const testFn = vi.fn();

const lifecycle = createLifecycleUtils();
const ExampleCleanupMolecule = molecule(() => {
onMount(() => {
testFn("mounted");
return () => testFn("unmounted");
});
testFn("created");
return testFn;
const uniqueValue = Math.random();
lifecycle.connect(uniqueValue);
return uniqueValue;
});

const injector = createInjector();

// FIXME: Would be very handy to be able to use globally scoped molecules
expect(() => injector.get(ExampleCleanupMolecule)).toThrowError();
lifecycle.expectUncalled();
const [value, unsub] = injector.use(ExampleCleanupMolecule);
lifecycle.expectActivelyMounted();

unsub();

lifecycle.expectToHaveBeenCalledTimes(1);
lifecycle.expectToMatchCalls([value]);
});

describe("Conditional dependencies", () => {
Expand Down

0 comments on commit a259729

Please sign in to comment.