Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: update parent checkbox state when new children are added dynamically #2145

Merged
merged 5 commits into from
Oct 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ describe('CheckboxGroup', () => {
it('should match standard snapshot', async () => {
const page = await newSpecPage({
components: [CheckboxGroup],
html: ` <scale-checkbox-group>
html: `<scale-checkbox-group>
<div slot="checkbox-header">
<scale-checkbox
input-id="header-checkbox"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import statusNote from '../../utils/status-note';
shadow: false,
})
export class CheckboxGroup {
observer: MutationObserver;

@Element() host: HTMLElement;

/** (optional) Input name */
Expand Down Expand Up @@ -95,6 +97,24 @@ export class CheckboxGroup {
}
}

componentDidLoad() {
this.updateParentCheckboxState();
const fieldset = this.host.querySelector('fieldset');
const mo = new MutationObserver(() => {
this.updateParentCheckboxState();
});
mo.observe(fieldset, {
childList: true,
});
this.observer = mo;
}

disconnectedCallback() {
if (this.observer) {
this.observer.disconnect();
}
}

getChildNodes() {
return Array.from(
this.host.querySelector('fieldset').querySelectorAll('scale-checkbox')
Expand Down Expand Up @@ -161,8 +181,4 @@ export class CheckboxGroup {
</Host>
);
}

componentDidLoad() {
this.updateParentCheckboxState();
}
}
1 change: 1 addition & 0 deletions packages/components/stencil.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export const config: Config = {
'!**/node_modules/**',
'!**/*.{d,esm,iife,styles}.ts',
],
setupFilesAfterEnv: ['./test-setup.ts'],
},
namespace: 'scale-components',
globalScript: 'src/global/scale.ts',
Expand Down
11 changes: 11 additions & 0 deletions packages/components/test-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const mutationObserverMock = jest.fn(function MutationObserver(callback) {
this.observe = jest.fn();
this.disconnect = jest.fn();
// // Optionally add a trigger() method to manually trigger a change
this.trigger = (mockedMutationsList) => {
callback(mockedMutationsList, this);
};
});

// Mock the global MutationObserver object
global.MutationObserver = mutationObserverMock as jest.Mock;
Loading