Skip to content

Commit

Permalink
fix: update parent checkbox state when new children are added dynamic…
Browse files Browse the repository at this point in the history
…ally (#2145)

* fix: update parent checkbox state when new children are added dynamically
  • Loading branch information
felix-ico authored Oct 12, 2023
1 parent 0ef89a0 commit 5d8d71f
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 5 deletions.
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;

0 comments on commit 5d8d71f

Please sign in to comment.