Skip to content

Commit d5211f9

Browse files
web-padawanclaude
andauthored
feat: update checkValidity to use dateMetadataProvider, add clearCache (#12276)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
1 parent 935c255 commit d5211f9

7 files changed

Lines changed: 510 additions & 50 deletions

‎packages/date-picker/ARCHITECTURE.md‎

Lines changed: 40 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,17 @@ further metadata extends the same entry shape.
1818
an unset property as `undefined` does not look like a change. Assigning a new function resets the cache.
1919
Callers are expected to keep a stable reference instead of passing a fresh function on every update.
2020

21+
`clearCache()` exists because of that reference comparison: re-fetching after the data behind the provider
22+
changed would otherwise mean handing over a new function, which conflates "ask again" with "ask something
23+
else". The two are the same operation internally, and differ only in whether the function is replaced.
24+
2125
## Where the cache lives
2226

2327
The date-picker element owns the controller, not the overlay content — which exists only once the overlay
2428
has been opened. Keeping it on the element is what makes the cache survive opening and closing, and a value
2529
can be set or typed without the overlay ever being opened. Checking such a value against the provider is
26-
what the ownership is for; the field's validity does not consult the provider yet, so for now the cache is
27-
filled only once the overlay has been opened.
30+
what the ownership is for: setting or typing a value loads the month holding it even if the overlay is
31+
never opened (see [When a value counts as valid](#when-a-value-counts-as-valid)).
2832

2933
The month calendars therefore read a controller they do not own. That is why change notification is
3034
explicit rather than a property assignment (see [How consumers are notified](#how-consumers-are-notified)).
@@ -82,9 +86,11 @@ provider afterwards. Reopening does not change what the calendars are configured
8286
debounced load; the cache survives close and reopen, so there is usually nothing left to fetch.
8387

8488
The visible range is also refilled when the cache is dropped, which nothing else would ask for again. That
85-
happens where the cache is dropped, on a provider change, and deliberately not from the controller's
86-
notification: a month whose request failed becomes missing again, so refilling on every notification would
87-
make a provider that throws or rejects retry without ever stopping.
89+
is done at each of the two places that drop it — a provider change and `clearCache()` — and deliberately
90+
not from the controller's notification: a month whose request failed is dropped and so becomes missing
91+
again, and refilling on every notification would make a provider that throws or rejects retry without ever
92+
stopping. Both places also reload the month holding the value, which the overlay does not cover while it
93+
is closed.
8894

8995
## What the cache holds
9096

@@ -118,11 +124,10 @@ true if a per-month refresh is ever added.
118124
The controller's `isDateDisabled` is true when the date's month is resolved **and** its metadata says so. A
119125
date whose month is still being fetched is not disabled; it is re-checked when the month resolves.
120126

121-
Being optimistic and correcting afterwards keeps rendering and selection consistent with each other,
122-
because both read the same predicate; validation is meant to join them and does not consult the provider
123-
yet. The alternative — treating an unresolved date as unusable — would make the whole visible calendar go
124-
dead while a slow provider answers, and report a value invalid on every fresh load, before anything is
125-
known about it.
127+
Being optimistic and correcting afterwards keeps rendering, selection and validation consistent with each
128+
other, because all three read the same predicate. The alternative — treating an unresolved date as unusable
129+
— would make the whole visible calendar go dead while a slow provider answers, and report a value invalid on
130+
every fresh load, before anything is known about it.
126131

127132
Dates in a month that is still being fetched render with a `loading` part while the spinner is shown, but
128133
they stay selectable. The cache calls such a month `pending` and the part is named for what the user sees,
@@ -147,8 +152,31 @@ predicate above already says about them.
147152
A date picked from a pending month is committed straight away. Holding the overlay open until the answer
148153
arrived would reintroduce blocking at the last moment, and leave the overlay stuck open on a provider that
149154
never answers. The window is narrow: reaching a pending month means navigating into a block that has not
150-
been loaded yet and clicking before it answers. Correcting such a commit once the month resolves needs
151-
validation to consult the provider, which it does not do yet.
155+
been loaded yet and clicking before it answers. Such a commit is corrected once the month resolves, by the
156+
re-validation below reporting the value invalid.
157+
158+
## When a value counts as valid
159+
160+
Validity reads the same predicate, so what the calendar refuses to select is what the field reports as
161+
invalid. A value can also be set programmatically or typed without the overlay ever opening, and nothing
162+
would have asked the provider about its month, so setting one loads that month on its own.
163+
164+
**The value is valid until the provider says otherwise.** While the month is on its way the date counts as
165+
allowed, and validation runs again once the answer arrives. `checkValidity()` is therefore time-dependent:
166+
it can report a value as valid and then invalid a moment later. The alternative — treating an unanswered
167+
date as invalid — would flash an error on every fresh load, before anything is known about the value, which
168+
is the failure this window exists to avoid.
169+
170+
Re-validation is driven from the host callback rather than from the request, because only the callback
171+
knows the month has arrived. It is armed when the load starts and disarmed when it fires — and re-decided
172+
on every value and provider change, so clearing the value or removing the provider mid-flight disarms it.
173+
An answer therefore never re-validates a value that was not waiting for it. Removing the provider is the
174+
one change with no answer to wait for: it lifts a constraint, so the value is re-checked right away. The
175+
callback runs whether or not the overlay was ever opened; the parts that update the spinner and the today
176+
button are the ones that need it open.
177+
178+
A value whose month resolved while the field was detached is validated when it is attached again, since the
179+
controller re-reports its state on reconnect and the armed flag is still set.
152180

153181
## How consumers are notified
154182

‎packages/date-picker/src/vaadin-date-picker-mixin.d.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -299,11 +299,16 @@ export declare class DatePickerMixinClass {
299299
*
300300
* `disabled` from the metadata is combined with `min`, `max` and `isDateDisabled`: a date is
301301
* disabled if it is out of the min/max range, or `isDateDisabled` returns `true`, or its metadata
302-
* marks it disabled. That decides what the calendar renders as disabled and what can be selected;
303-
* the field's validity is not yet checked against the provider.
302+
* marks it disabled. That decides what the calendar renders as disabled, what can be selected, and
303+
* whether the field is valid.
304304
*
305-
* Keep a stable reference to the function; assigning a new one clears the cache and re-fetches
306-
* every visible range.
305+
* A value is checked against the provider even if the overlay is never opened, which loads the
306+
* month holding it. Until that month answers the value is valid, and it is re-validated once the
307+
* answer arrives, so `checkValidity()` can report a value as valid and then invalid.
308+
*
309+
* Keep a stable reference to the function. Assigning a new function clears the cache and
310+
* re-fetches every visible range. To re-fetch while keeping the same function, because the data
311+
* behind it changed, call `clearCache()`.
307312
*/
308313
dateMetadataProvider: DatePickerDateMetadataProvider | null | undefined;
309314

@@ -316,4 +321,9 @@ export declare class DatePickerMixinClass {
316321
* Closes the dropdown.
317322
*/
318323
close(): void;
324+
325+
/**
326+
* Clears the `dateMetadataProvider` cache and reloads the date metadata.
327+
*/
328+
clearCache(): void;
319329
}

‎packages/date-picker/src/vaadin-date-picker-mixin.js‎

Lines changed: 75 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { DateMetadataController } from './vaadin-date-metadata-controller.js';
1717
import {
1818
dateAllowed,
1919
dateEquals,
20+
dateSelectable,
2021
extractDateParts,
2122
formatISODate,
2223
getAdjustedYear,
@@ -232,11 +233,16 @@ export const DatePickerMixin = (subclass) =>
232233
*
233234
* `disabled` from the metadata is combined with `min`, `max` and `isDateDisabled`: a date is
234235
* disabled if it is out of the min/max range, or `isDateDisabled` returns `true`, or its
235-
* metadata marks it disabled. That decides what the calendar renders as disabled and what can
236-
* be selected; the field's validity is not yet checked against the provider.
236+
* metadata marks it disabled. That decides what the calendar renders as disabled, what can be
237+
* selected, and whether the field is valid.
237238
*
238-
* Keep a stable reference to the function; assigning a new one clears the cache and re-fetches
239-
* every visible range.
239+
* A value is checked against the provider even if the overlay is never opened, which loads the
240+
* month holding it. Until that month answers the value is valid, and it is re-validated once
241+
* the answer arrives, so `checkValidity()` can report a value as valid and then invalid.
242+
*
243+
* Keep a stable reference to the function. Assigning a new function clears the cache and
244+
* re-fetches every visible range. To re-fetch while keeping the same function, because the
245+
* data behind it changed, call `clearCache()`.
240246
*
241247
* @type {DatePickerDateMetadataProvider | null | undefined}
242248
*/
@@ -308,7 +314,7 @@ export const DatePickerMixin = (subclass) =>
308314
}
309315

310316
static get constraints() {
311-
return [...super.constraints, 'min', 'max'];
317+
return [...super.constraints, 'min', 'max', 'dateMetadataProvider'];
312318
}
313319

314320
constructor() {
@@ -489,9 +495,7 @@ export const DatePickerMixin = (subclass) =>
489495

490496
if (props.has('dateMetadataProvider')) {
491497
this._dateMetadataController.setProvider(this.dateMetadataProvider);
492-
if (this.opened) {
493-
this._overlayContent?.loadVisibleDateMetadata();
494-
}
498+
this.__reloadDateMetadata();
495499
}
496500

497501
if (props.has('showWeekNumbers') || props.has('__effectiveI18n')) {
@@ -536,6 +540,28 @@ export const DatePickerMixin = (subclass) =>
536540
this.$.overlay.close();
537541
}
538542

543+
/**
544+
* Clears the `dateMetadataProvider` cache and reloads the date metadata.
545+
*/
546+
clearCache() {
547+
this._dateMetadataController.clearCache();
548+
this.__reloadDateMetadata();
549+
}
550+
551+
/**
552+
* Asks for what the dropped cache was holding: the months the overlay is showing, and the month
553+
* of the value being validated. Requested from here rather than from the controller's
554+
* notification, which would turn a provider that keeps failing into an endless retry, since a
555+
* failed month is dropped and so becomes missing again.
556+
* @private
557+
*/
558+
__reloadDateMetadata() {
559+
if (this.opened) {
560+
this._overlayContent?.loadVisibleDateMetadata();
561+
}
562+
this.__ensureSelectedDateLoaded();
563+
}
564+
539565
/** @private */
540566
__ensureContent() {
541567
if (this._overlayContent) {
@@ -628,7 +654,14 @@ export const DatePickerMixin = (subclass) =>
628654
const inputValue = this._inputElementValue;
629655
const inputValid = !inputValue || (!!this._selectedDate && inputValue === this.__formatDate(this._selectedDate));
630656
const isDateValid =
631-
!this._selectedDate || dateAllowed(this._selectedDate, this._minDate, this._maxDate, this.isDateDisabled);
657+
!this._selectedDate ||
658+
dateSelectable(
659+
this._selectedDate,
660+
this._minDate,
661+
this._maxDate,
662+
this.isDateDisabled,
663+
this._dateMetadataController,
664+
);
632665

633666
let inputValidity = true;
634667
if (this.inputElement && this.inputElement.checkValidity) {
@@ -638,18 +671,45 @@ export const DatePickerMixin = (subclass) =>
638671
return inputValid && isDateValid && inputValidity;
639672
}
640673

674+
/**
675+
* Asks the controller for the month holding the selected date, so a value that was set or typed
676+
* without ever opening the overlay is still checked against the provider. Validation is re-run
677+
* from the host callback once the month resolves.
678+
* @private
679+
*/
680+
__ensureSelectedDateLoaded() {
681+
const controller = this._dateMetadataController;
682+
const awaiting = !!(controller?.provider && this._selectedDate && !controller.isMonthLoaded(this._selectedDate));
683+
// Always assigned, so clearing the value or removing the provider while a request is in
684+
// flight disarms the pending re-validation, and a later answer for some other month does not
685+
// re-validate a value that never waited for it.
686+
this.__awaitingProviderValidation = awaiting;
687+
if (awaiting) {
688+
controller.ensureRangeLoaded(this._selectedDate, this._selectedDate);
689+
}
690+
}
691+
641692
/**
642693
* Called by the date metadata controller, one microtask after its state changed
643694
* and coalesced, so this never writes reactive state from inside an update. The
644695
* rendered months refresh on their own because they subscribe to the controller.
645696
* @private
646697
*/
647698
__onDateMetadataChanged() {
648-
if (!this._overlayContent) {
649-
return;
699+
const controller = this._dateMetadataController;
700+
701+
// Only the open overlay has a spinner to update and a today button to re-evaluate.
702+
if (this._overlayContent) {
703+
this._overlayContent.loading = controller.isLoading();
704+
this._overlayContent.updateTodayButton();
705+
}
706+
707+
// Runs whether or not the overlay was ever opened, which is the case this exists for: a value
708+
// set or typed with the overlay closed is reported invalid as soon as its month answers.
709+
if (this.__awaitingProviderValidation && this._selectedDate && controller.isMonthLoaded(this._selectedDate)) {
710+
this.__awaitingProviderValidation = false;
711+
this._requestValidation();
650712
}
651-
this._overlayContent.loading = this._dateMetadataController.isLoading();
652-
this._overlayContent.updateTodayButton();
653713
}
654714

655715
/**
@@ -839,6 +899,8 @@ export const DatePickerMixin = (subclass) =>
839899
this._ignoreFocusedDateChange = true;
840900
this._focusedDate = selectedDate;
841901
this._ignoreFocusedDateChange = false;
902+
903+
this.__ensureSelectedDateLoaded();
842904
}
843905

844906
/** @private */
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import { expect } from '@vaadin/chai-plugins';
2+
import { aTimeout, fixtureSync, nextRender } from '@vaadin/testing-helpers';
3+
import sinon from 'sinon';
4+
import '../src/vaadin-date-picker.js';
5+
import { getDateCell, getMonthCalendar, open } from './helpers.js';
6+
7+
describe('dateMetadataProvider clearCache', () => {
8+
let datePicker, overlayContent, year, month;
9+
10+
function getCell(day) {
11+
return getDateCell(getMonthCalendar(overlayContent, year, month), day);
12+
}
13+
14+
// The reactive chain after a provider resolves can span more than one render.
15+
async function untilRendered(predicate) {
16+
for (let i = 0; i < 50 && !predicate(); i++) {
17+
await nextRender();
18+
}
19+
await nextRender();
20+
}
21+
22+
beforeEach(async () => {
23+
const today = new Date();
24+
year = today.getFullYear();
25+
month = today.getMonth();
26+
datePicker = fixtureSync('<vaadin-date-picker></vaadin-date-picker>');
27+
await nextRender();
28+
});
29+
30+
it('should ask the provider again for the months on screen', async () => {
31+
const provider = sinon.stub().returns([]);
32+
datePicker.dateMetadataProvider = provider;
33+
await open(datePicker);
34+
overlayContent = datePicker._overlayContent;
35+
await nextRender();
36+
provider.resetHistory();
37+
38+
datePicker.clearCache();
39+
await nextRender();
40+
41+
expect(provider).to.be.called;
42+
});
43+
44+
it('should reflect metadata that changed behind the provider', async () => {
45+
let disabledDay = 10;
46+
datePicker.dateMetadataProvider = () => [{ year, month, day: disabledDay, disabled: true }];
47+
await open(datePicker);
48+
overlayContent = datePicker._overlayContent;
49+
await untilRendered(() => getCell(10)?.hasAttribute('disabled'));
50+
expect(getCell(10).hasAttribute('disabled')).to.be.true;
51+
52+
disabledDay = 11;
53+
datePicker.clearCache();
54+
await untilRendered(() => getCell(11)?.hasAttribute('disabled'));
55+
56+
expect(getCell(11).hasAttribute('disabled')).to.be.true;
57+
expect(getCell(10).hasAttribute('disabled')).to.be.false;
58+
});
59+
60+
it('should keep the same provider function', async () => {
61+
const provider = sinon.stub().returns([]);
62+
datePicker.dateMetadataProvider = provider;
63+
await nextRender();
64+
65+
datePicker.clearCache();
66+
await aTimeout(0);
67+
68+
expect(datePicker.dateMetadataProvider).to.equal(provider);
69+
});
70+
71+
it('should re-validate the value while the overlay is closed', async () => {
72+
let disabled = false;
73+
datePicker.dateMetadataProvider = () => (disabled ? [{ year: 2024, month: 0, day: 15, disabled: true }] : []);
74+
datePicker.value = '2024-01-15';
75+
await aTimeout(0);
76+
expect(datePicker.invalid).to.be.false;
77+
78+
disabled = true;
79+
datePicker.clearCache();
80+
await aTimeout(0);
81+
82+
expect(datePicker.invalid).to.be.true;
83+
});
84+
85+
it('should not re-request in a loop when the provider keeps failing', async () => {
86+
const provider = sinon.stub().throws(new Error('provider failed'));
87+
const error = sinon.stub(console, 'error');
88+
datePicker.dateMetadataProvider = provider;
89+
await open(datePicker);
90+
overlayContent = datePicker._overlayContent;
91+
await nextRender();
92+
provider.resetHistory();
93+
94+
datePicker.clearCache();
95+
await aTimeout(0);
96+
await aTimeout(0);
97+
98+
// A failed month becomes missing again, so refilling from the notification would never stop.
99+
expect(provider.callCount).to.be.below(4);
100+
error.restore();
101+
});
102+
103+
it('should not throw when no provider is set', async () => {
104+
await nextRender();
105+
expect(() => datePicker.clearCache()).to.not.throw();
106+
});
107+
});

0 commit comments

Comments
 (0)