TimeRangeProvider: Fix synced status being kept when only one picker is mounted (#95885)

This commit is contained in:
Andrej Ocenas 2024-11-06 13:40:17 +01:00 committed by GitHub
parent f15f6022de
commit 86ef3c916d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 46 additions and 1 deletions

View File

@ -79,6 +79,43 @@ describe('TimeRangeProvider', () => {
syncedValue: undefined,
});
});
it('sets status to not synced if only 1 component remains', async () => {
let context2: TimeRangeContextHookValue | undefined = undefined;
function onContextChange2(val?: TimeRangeContextHookValue) {
context2 = val;
}
const renderContext = render(
<TimeRangeProvider>
<TestComponent onContextChange={onContextChange} />
<TestComponent onContextChange={onContextChange2} />
</TimeRangeProvider>
);
const timeRange = makeTimeRange('2021-01-01', '2021-01-02');
act(() => {
context?.sync(timeRange);
});
expect(context2).toMatchObject({
syncPossible: true,
synced: true,
syncedValue: timeRange,
});
renderContext.rerender(
<TimeRangeProvider>
<TestComponent onContextChange={onContextChange2} />
</TimeRangeProvider>
);
expect(context2).toMatchObject({
syncPossible: false,
synced: false,
syncedValue: undefined,
});
});
});
describe('useTimeRangeContext', () => {

View File

@ -42,7 +42,15 @@ export function TimeRangeProvider({ children }: { children: ReactNode }) {
sync: (value: TimeRange) => setSyncedValue(value),
unSync: () => setSyncedValue(undefined),
addPicker: () => setPickersCount((val) => val + 1),
removePicker: () => setPickersCount((val) => val - 1),
removePicker: () => {
setPickersCount((val) => {
const newVal = val - 1;
if (newVal < 2) {
setSyncedValue(undefined);
}
return newVal;
});
},
syncPossible: pickersCount > 1,
synced: Boolean(syncedValue),
syncedValue,