Skip to content

Commit

Permalink
Avoid infinite loops when reading context values at construct time
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinkucharczyk committed Nov 26, 2024
1 parent 48f7bee commit e01f472
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/strange-dolls-refuse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ember-provide-consume-context": patch
---

Avoid infinite loops when reading context values at construct time
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,7 @@ export class ProvideConsumeContextContainer {

private registerComponent(component: any) {
const currentContexts = this.currentContexts();

// If a current context reference or global contexts exist, register them to the component
if (Object.keys(currentContexts).length > 0) {
this.contexts.set(component, currentContexts);
}
this.contexts.set(component, currentContexts);
}

currentContexts() {
Expand Down
56 changes: 56 additions & 0 deletions test-app/tests/integration/components/decorators-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -972,4 +972,60 @@ module('Integration | Decorators', function (hooks) {
assert.dom('#content-1').hasText('1');
assert.dom('#content-2').hasText('2');
});

test('provider that references its own context and reading context value at construct time', async function (assert) {
class TestProviderComponent extends Component<{
Element: HTMLDivElement;
Blocks: {
default: [];
};
}> {
@consume('my-test-context') parentContextValue!: number;

get nextContextValue() {
return (this.parentContextValue ?? 0) + 1;
}
}

setComponentTemplate(
// @ts-ignore
hbs`{{! @glint-ignore }}
<ContextProvider @key="my-test-context" @value={{this.nextContextValue}}>{{yield}}</ContextProvider>
`,
TestProviderComponent,
);

class TestConsumerComponent extends Component<{
Element: HTMLDivElement;
}> {
@consume('my-test-context') contextValue!: number;

readValue = this.contextValue;
}

setComponentTemplate(
// @ts-ignore
hbs`{{! @glint-ignore }}
<div id="content">{{this.readValue}}</div>
`,
TestConsumerComponent,
);

interface TestContext {
TestProviderComponent: typeof TestProviderComponent;
TestConsumerComponent: typeof TestConsumerComponent;
}
(this as unknown as TestContext).TestProviderComponent =
TestProviderComponent;
(this as unknown as TestContext).TestConsumerComponent =
TestConsumerComponent;

await render<TestContext>(hbs`
<this.TestProviderComponent>
<this.TestConsumerComponent />
</this.TestProviderComponent>
`);

assert.dom('#content').hasText('1');
});
});

0 comments on commit e01f472

Please sign in to comment.