You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@causeway.apache.org by da...@apache.org on 2026/08/30 18:35:54 UTC

(causeway) 05/07: fix(webcomponents): localize date picker access

This is an automated email from the ASF dual-hosted git repository.

danhaywood pushed a commit to branch htmx
in repository https://gitbox.apache.org/repos/asf/causeway.git

commit 6d2b23896b4a7c068e6b56863838ee1c2e57356d
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Sun Aug 30 20:28:29 2026 +0200

    fix(webcomponents): localize date picker access
---
 .../localize-date-editor-accessibility/tasks.md    |  18 +--
 viewers/webcomponents/foundation/USAGE.adoc        |   4 +
 .../webcomponents/foundation/src/field-widget.mjs  | 173 ++++++++++++++++++++-
 .../foundation/test/field-widget.test.mjs          |  70 +++++++++
 .../petclinic/PetClinicHtmxPlaywrightTest.java     |  26 +++-
 5 files changed, 280 insertions(+), 11 deletions(-)

diff --git a/openspec/changes/localize-date-editor-accessibility/tasks.md b/openspec/changes/localize-date-editor-accessibility/tasks.md
index ef1da987ee2..cf10e73c763 100644
--- a/openspec/changes/localize-date-editor-accessibility/tasks.md
+++ b/openspec/changes/localize-date-editor-accessibility/tasks.md
@@ -1,17 +1,17 @@
 ## 1. Locale-Aware Date Adapter
 
-- [ ] 1.1 Add bounded locale resolution and reversible `Intl`-based date formatting, parsing, localized calendar labels, and optional first-weekday configuration.
-- [ ] 1.2 Apply locale configuration to qualified `LocalDate` and `LocalDateTime` controls without changing their ISO semantic values.
-- [ ] 1.3 Add unit tests for document-language precedence, browser fallback, locale date order, localized digits, ISO correction input, invalid dates, and safe locale fallback.
+- [x] 1.1 Add bounded locale resolution and reversible `Intl`-based date formatting, parsing, localized calendar labels, and optional first-weekday configuration.
+- [x] 1.2 Apply locale configuration to qualified `LocalDate` and `LocalDateTime` controls without changing their ISO semantic values.
+- [x] 1.3 Add unit tests for document-language precedence, browser fallback, locale date order, localized digits, ISO correction input, invalid dates, and safe locale fallback.
 
 ## 2. Keyboard Calendar Access
 
-- [ ] 2.1 Qualify editable Vaadin date-picker calendar triggers with button semantics, field-specific accessible names, Tab focus, and Enter or Space activation.
-- [ ] 2.2 Keep focus transitions to the shadow-DOM trigger inside the active Causeway editor and exclude read-only or disabled triggers.
-- [ ] 2.3 Add unit and actual Vaadin-backed browser assertions for trigger focus, accessible naming, activation, localized display, and unchanged pending interaction behavior.
+- [x] 2.1 Qualify editable Vaadin date-picker calendar triggers with button semantics, field-specific accessible names, Tab focus, and Enter or Space activation.
+- [x] 2.2 Keep focus transitions to the shadow-DOM trigger inside the active Causeway editor and exclude read-only or disabled triggers.
+- [x] 2.3 Add unit and actual Vaadin-backed browser assertions for trigger focus, accessible naming, activation, localized display, and unchanged pending interaction behavior.
 
 ## 3. Documentation and Verification
 
-- [ ] 3.1 Document locale precedence, accepted date entry, preserved ISO semantics, and calendar-trigger keyboard operation.
-- [ ] 3.2 Run the complete foundation test suite and applicable Vaadin/Petclinic build checks.
-- [ ] 3.3 Run strict OpenSpec validation and verify a clean implementation diff.
+- [x] 3.1 Document locale precedence, accepted date entry, preserved ISO semantics, and calendar-trigger keyboard operation.
+- [x] 3.2 Run the complete foundation test suite and applicable Vaadin/Petclinic build checks.
+- [x] 3.3 Run strict OpenSpec validation and verify a clean implementation diff.
diff --git a/viewers/webcomponents/foundation/USAGE.adoc b/viewers/webcomponents/foundation/USAGE.adoc
index 0b78d2ea845..7a4e96de8ef 100644
--- a/viewers/webcomponents/foundation/USAGE.adoc
+++ b/viewers/webcomponents/foundation/USAGE.adoc
@@ -656,6 +656,10 @@ configureCausewayFieldWidgets({families: [], presentation: false});
 `basic` covers reversible text, multiline, protected, Boolean, enum, bounded scalar choice, and URL inputs.
 `numeric` keeps `Long`, `BigInteger`, and `BigDecimal` lexical in text fields while using integer or number controls only for machine numeric codecs.
 `local-temporal` covers `LocalDate`, `LocalTime`, and `LocalDateTime`; values beyond millisecond fractional precision remain native because the picker cannot preserve them.
+Local dates use the nonblank document `lang`, then the browser locale, then `en` to format and parse the visible date while preserving the ISO value passed to Causeway codecs and GraphQL.
+Localized numeric input and unambiguous ISO `yyyy-MM-dd` input are accepted, and available locale calendar names and first-weekday settings are applied to the picker.
+In an editable Vaadin date picker, Tab moves from the date input to the labelled calendar button, and Enter or Space opens the calendar without committing or cancelling the Causeway interaction.
+Read-only and disabled date controls do not expose that operable calendar button.
 Offset, zoned, legacy temporal, Blob, Clob, resource, custom, reference, collection, and unsupported values never become eligible field adapters.
 References retain their separate adapter.
 
diff --git a/viewers/webcomponents/foundation/src/field-widget.mjs b/viewers/webcomponents/foundation/src/field-widget.mjs
index 87d61ec2f54..2ceb6a702ae 100644
--- a/viewers/webcomponents/foundation/src/field-widget.mjs
+++ b/viewers/webcomponents/foundation/src/field-widget.mjs
@@ -30,6 +30,8 @@ let configuration = Object.freeze({
 });
 const familyModules = new Map();
 const failedFamilies = new Set();
+const qualifiedCalendarTriggers = new WeakSet();
+const BIDI_CONTROL_PATTERN = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu;
 let configurationRevision = 0;
 
 const documentPolicy = globalThis.document?.documentElement?.dataset;
@@ -64,6 +66,79 @@ export function causewayFieldWidgetConfiguration() {
   return configuration;
 }
 
+export function resolveCausewayDateLocale(documentLanguage = globalThis.document?.documentElement?.lang,
+    browserLanguage = globalThis.navigator?.language) {
+  for (const candidate of [documentLanguage, browserLanguage, 'en']) {
+    const bounded = String(candidate ?? '').trim().slice(0, 80);
+    if (!bounded) continue;
+    try {
+      return new Intl.Locale(bounded).toString();
+    } catch {
+      // Try the next bounded locale candidate.
+    }
+  }
+  return 'en';
+}
+
+export function causewayDatePickerI18n(locale = resolveCausewayDateLocale()) {
+  const resolvedLocale = resolveCausewayDateLocale(locale, 'en');
+  const options = {calendar: 'gregory', timeZone: 'UTC'};
+  const formatter = new Intl.DateTimeFormat(resolvedLocale, {...options, year: 'numeric', month: 'numeric', day: 'numeric'});
+  const patternParts = formatter.formatToParts(calendarDate(2006, 10, 22));
+  const digitMap = localeDigitMap(resolvedLocale);
+  const parsePattern = localizedDatePattern(patternParts);
+  const localeInfo = new Intl.Locale(resolvedLocale);
+  const weekInfo = typeof localeInfo.getWeekInfo === 'function' ? localeInfo.getWeekInfo() : localeInfo.weekInfo;
+  const i18n = {
+    monthNames: Array.from({length: 12}, (_, month) => new Intl.DateTimeFormat(resolvedLocale, {
+      ...options, month: 'long'
+    }).format(calendarDate(2006, month, 1))),
+    weekdays: Array.from({length: 7}, (_, day) => new Intl.DateTimeFormat(resolvedLocale, {
+      ...options, weekday: 'long'
+    }).format(calendarDate(2006, 0, day + 1))),
+    weekdaysShort: Array.from({length: 7}, (_, day) => new Intl.DateTimeFormat(resolvedLocale, {
+      ...options, weekday: 'short'
+    }).format(calendarDate(2006, 0, day + 1))),
+    formatDate: parts => validCalendarParts(parts?.year, parts?.month, parts?.day)
+      ? formatter.format(calendarDate(parts.year, parts.month, parts.day))
+      : '',
+    parseDate: value => parseLocalizedDate(value, parsePattern, digitMap)
+  };
+  if (Number.isInteger(weekInfo?.firstDay)) i18n.firstDayOfWeek = weekInfo.firstDay % 7;
+  return Object.freeze(i18n);
+}
+
+export function qualifyCausewayCalendarTrigger(datePicker, label, operable = true) {
+  const trigger = datePicker?.shadowRoot?.querySelector?.('[part~="toggle-button"]');
+  if (!trigger || !operable || datePicker.disabled || datePicker.readOnly || datePicker.readonly) return null;
+  trigger.removeAttribute('aria-hidden');
+  trigger.setAttribute('role', 'button');
+  trigger.setAttribute('tabindex', '0');
+  trigger.setAttribute('aria-label', `Open ${boundedLabel(label)} calendar`);
+  trigger.setAttribute('data-causeway-calendar-trigger', '');
+  if (!qualifiedCalendarTriggers.has(trigger)) {
+    const input = datePicker.inputElement;
+    input?.addEventListener?.('keydown', event => {
+      if (event.key !== 'Tab' || event.shiftKey) return;
+      event.preventDefault();
+      trigger.focus();
+    }, {capture: true});
+    trigger.addEventListener('keydown', event => {
+      if (event.key === 'Tab' && event.shiftKey && input?.focus) {
+        event.preventDefault();
+        input.focus();
+        return;
+      }
+      if (!['Enter', ' '].includes(event.key)) return;
+      event.preventDefault();
+      event.stopPropagation();
+      trigger.click();
+    });
+    qualifiedCalendarTriggers.add(trigger);
+  }
+  return trigger;
+}
+
 export function failCausewayFieldFamily(family, {announce = true} = {}) {
   if (!FAMILY_IDS.includes(family) || failedFamilies.has(family)) return false;
   failedFamilies.add(family);
@@ -294,6 +369,10 @@ export class CausewayFieldEditorElement extends HTMLElement {
       control.disabled = !viewMode && this.hasAttribute('disabled');
       control.required = !viewMode && this.hasAttribute('required');
       control.invalid = !viewMode && this.dataset.invalid === 'true';
+      const dateI18n = ['date-picker', 'date-time-picker'].includes(this.dataset.control)
+        ? causewayDatePickerI18n()
+        : null;
+      if (dateI18n) control.i18n = {...control.i18n, ...dateI18n};
       const supportsClearButton = 'clearButtonVisible' in control;
       if (supportsClearButton) control.clearButtonVisible = false;
       if (!viewMode) {
@@ -302,7 +381,7 @@ export class CausewayFieldEditorElement extends HTMLElement {
             return;
           }
           event.stopPropagation();
-          if (control.contains(event.relatedTarget)) {
+          if (shadowIncludingContains(control, event.relatedTarget)) {
             return;
           }
           this.dispatchEvent(new CustomEvent('causeway-editor-commit', {
@@ -345,7 +424,16 @@ export class CausewayFieldEditorElement extends HTMLElement {
         const suffix = field.localName === 'vaadin-date-picker' ? 'date' : 'time';
         field.accessibleName = `${this.dataset.label ?? ''} ${suffix}`.trim();
       }
+      const datePickers = datePickerControls(control);
+      for (const field of datePickers) {
+        if (dateI18n && field !== control) field.i18n = {...field.i18n, ...dateI18n};
+      }
       await Promise.all(compositeFields.map(field => field.updateComplete));
+      if (!viewMode) {
+        for (const field of datePickers) {
+          scheduleCausewayCalendarTrigger(field, this.dataset.label, !control.disabled);
+        }
+      }
       if (!this.isConnected || generation !== this._generation || revision !== configurationRevision) return;
       if (this.dataset.describedby) {
         for (const input of accessibleFieldInputs(control)) {
@@ -429,6 +517,89 @@ export class CausewayFieldEditorElement extends HTMLElement {
   }
 }
 
+function calendarDate(year, month, day) {
+  const date = new Date(0);
+  date.setUTCHours(0, 0, 0, 0);
+  date.setUTCFullYear(Number(year), Number(month), Number(day));
+  return date;
+}
+
+function validCalendarParts(year, month, day) {
+  if (![year, month, day].every(Number.isInteger) || month < 0 || month > 11 || day < 1 || day > 31) return false;
+  const date = calendarDate(year, month, day);
+  return date.getUTCFullYear() === year && date.getUTCMonth() === month && date.getUTCDate() === day;
+}
+
+function localeDigitMap(locale) {
+  const formatter = new Intl.NumberFormat(locale, {useGrouping: false});
+  return new Map(Array.from({length: 10}, (_, digit) => [
+    formatter.format(digit).replace(BIDI_CONTROL_PATTERN, ''), String(digit)
+  ]));
+}
+
+function localizedDatePattern(parts) {
+  const fields = [];
+  const source = parts.map(part => {
+    if (['year', 'month', 'day'].includes(part.type)) {
+      fields.push(part.type);
+      return part.type === 'year' ? '(\\d{1,6})' : '(\\d{1,2})';
+    }
+    const literal = part.value.replace(BIDI_CONTROL_PATTERN, '');
+    return literal.split(/\s+/u).map(escapeRegExp).join('\\s*');
+  }).join('');
+  return Object.freeze({fields: Object.freeze(fields), regexp: new RegExp(`^\\s*${source}\\s*$`, 'u')});
+}
+
+function parseLocalizedDate(value, pattern, digitMap) {
+  let normalized = String(value ?? '').replace(BIDI_CONTROL_PATTERN, '').trim();
+  for (const [localized, ascii] of digitMap) {
+    if (localized) normalized = normalized.split(localized).join(ascii);
+  }
+  const iso = /^(\d{4,6})-(\d{2})-(\d{2})$/u.exec(normalized);
+  if (iso) return parsedCalendarParts(Number(iso[1]), Number(iso[2]), Number(iso[3]));
+  const match = pattern.regexp.exec(normalized);
+  if (!match) return undefined;
+  const values = Object.fromEntries(pattern.fields.map((field, index) => [field, Number(match[index + 1])]));
+  return parsedCalendarParts(values.year, values.month, values.day);
+}
+
+function parsedCalendarParts(year, oneBasedMonth, day) {
+  const month = oneBasedMonth - 1;
+  return validCalendarParts(year, month, day) ? {year, month, day} : undefined;
+}
+
+function escapeRegExp(value) {
+  return String(value).replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
+}
+
+function scheduleCausewayCalendarTrigger(datePicker, label, operable) {
+  if (qualifyCausewayCalendarTrigger(datePicker, label, operable) || !operable || !datePicker?.shadowRoot) return;
+  const observer = new MutationObserver(() => {
+    if (qualifyCausewayCalendarTrigger(datePicker, label, operable)) observer.disconnect();
+  });
+  observer.observe(datePicker.shadowRoot, {childList: true, subtree: true});
+  queueMicrotask(() => {
+    if (qualifyCausewayCalendarTrigger(datePicker, label, operable)) observer.disconnect();
+  });
+  setTimeout(() => observer.disconnect(), 1000);
+}
+
+function datePickerControls(control) {
+  const fields = control?.localName === 'vaadin-date-picker' ? [control] : [];
+  for (const root of [control, control?.shadowRoot]) {
+    fields.push(...(root?.querySelectorAll?.('vaadin-date-picker') ?? []));
+  }
+  return [...new Set(fields)];
+}
+
+function shadowIncludingContains(ancestor, candidate) {
+  for (let current = candidate; current;) {
+    if (current === ancestor) return true;
+    current = current.parentNode ?? current.getRootNode?.()?.host ?? null;
+  }
+  return false;
+}
+
 function compositeFieldControls(control) {
   const fields = [];
   for (const root of [control, control.shadowRoot]) {
diff --git a/viewers/webcomponents/foundation/test/field-widget.test.mjs b/viewers/webcomponents/foundation/test/field-widget.test.mjs
index e672e934677..1013fe01a42 100644
--- a/viewers/webcomponents/foundation/test/field-widget.test.mjs
+++ b/viewers/webcomponents/foundation/test/field-widget.test.mjs
@@ -14,12 +14,15 @@ import {installDomShim} from './dom-shim.mjs';
 installDomShim();
 const {
   CausewayFieldEditorElement,
+  causewayDatePickerI18n,
   causewayFieldDescriptor,
   causewayReadOnlyFieldDescriptor,
   causewayFieldWidgetConfiguration,
   configureCausewayFieldWidgets,
+  qualifyCausewayCalendarTrigger,
   renderCausewayFieldWidget,
   renderCausewayReadOnlyField,
+  resolveCausewayDateLocale,
   supportsCausewayFieldWidget,
   supportsCausewayReadOnlyField
 } = await import('../src/field-widget.mjs');
@@ -114,6 +117,73 @@ test('qualifies read-only families without exposing protected values', () => {
   assert.equal(supportsCausewayReadOnlyField(context()), false);
 });
 
+test('local date presentation follows bounded document and browser locales reversibly', () => {
+  assert.equal(resolveCausewayDateLocale('en-GB', 'en-US'), 'en-GB');
+  assert.equal(resolveCausewayDateLocale('%%%', 'de-DE'), 'de-DE');
+  assert.equal(resolveCausewayDateLocale('', ''), 'en');
+
+  const british = causewayDatePickerI18n('en-GB');
+  assert.equal(british.formatDate({year: 2026, month: 7, day: 30}), '30/08/2026');
+  assert.deepEqual(british.parseDate('30/08/2026'), {year: 2026, month: 7, day: 30});
+  assert.deepEqual(british.parseDate('2026-08-30'), {year: 2026, month: 7, day: 30});
+  assert.equal(british.parseDate('31/02/2026'), undefined);
+  assert.equal(british.firstDayOfWeek, 1);
+
+  const american = causewayDatePickerI18n('en-US');
+  assert.equal(american.formatDate({year: 2026, month: 7, day: 30}), '8/30/2026');
+  assert.deepEqual(american.parseDate('8/30/2026'), {year: 2026, month: 7, day: 30});
+  assert.equal(american.firstDayOfWeek, 0);
+
+  const arabic = causewayDatePickerI18n('ar-EG');
+  const localized = arabic.formatDate({year: 2026, month: 7, day: 30});
+  assert.deepEqual(arabic.parseDate(localized), {year: 2026, month: 7, day: 30});
+  assert.equal(arabic.monthNames.length, 12);
+  assert.equal(arabic.weekdays.length, 7);
+  assert.equal(arabic.weekdaysShort.length, 7);
+  assert.equal(causewayDatePickerI18n('%%%').formatDate({year: 2026, month: 7, day: 30}), '8/30/2026');
+});
+
+test('calendar trigger gains bounded button semantics and keyboard activation only when operable', () => {
+  const trigger = document.createElement('div');
+  trigger.setAttribute('aria-hidden', 'true');
+  let activations = 0;
+  trigger.click = () => { activations += 1; };
+  const input = document.createElement('input');
+  const picker = {
+    disabled: false,
+    readOnly: false,
+    inputElement: input,
+    shadowRoot: {querySelector: selector => selector === '[part~="toggle-button"]' ? trigger : null}
+  };
+  assert.equal(qualifyCausewayCalendarTrigger(picker, 'Last Visit'), trigger);
+  assert.equal(trigger.getAttribute('aria-hidden'), null);
+  assert.equal(trigger.getAttribute('role'), 'button');
+  assert.equal(trigger.getAttribute('tabindex'), '0');
+  assert.equal(trigger.getAttribute('aria-label'), 'Open Last Visit calendar');
+  assert.equal(trigger.hasAttribute('data-causeway-calendar-trigger'), true);
+  input.focus();
+  const forwardTab = new Event('keydown', {cancelable: true});
+  forwardTab.key = 'Tab';
+  input.dispatchEvent(forwardTab);
+  assert.equal(forwardTab.defaultPrevented, true);
+  assert.equal(document.activeElement, trigger);
+  const reverseTab = new Event('keydown', {cancelable: true});
+  reverseTab.key = 'Tab';
+  reverseTab.shiftKey = true;
+  trigger.dispatchEvent(reverseTab);
+  assert.equal(reverseTab.defaultPrevented, true);
+  assert.equal(document.activeElement, input);
+  for (const key of ['Enter', ' ']) {
+    const event = new Event('keydown', {cancelable: true});
+    event.key = key;
+    trigger.dispatchEvent(event);
+    assert.equal(event.defaultPrevented, true);
+  }
+  assert.equal(activations, 2);
+  assert.equal(qualifyCausewayCalendarTrigger({...picker, readOnly: true}, 'Last Visit'), null);
+  assert.equal(qualifyCausewayCalendarTrigger({...picker, disabled: true}, 'Last Visit'), null);
+});
+
 test('keeps protected values out of adapter markup', () => {
   configureCausewayFieldWidgets({families: ['basic']});
   const html = renderCausewayFieldWidget(context({
diff --git a/viewers/webcomponents/sample-htmx-petclinic/src/playwright/java/org/apache/causeway/viewer/webcomponents/sample/htmx/petclinic/PetClinicHtmxPlaywrightTest.java b/viewers/webcomponents/sample-htmx-petclinic/src/playwright/java/org/apache/causeway/viewer/webcomponents/sample/htmx/petclinic/PetClinicHtmxPlaywrightTest.java
index e79716c7699..a71318368bb 100644
--- a/viewers/webcomponents/sample-htmx-petclinic/src/playwright/java/org/apache/causeway/viewer/webcomponents/sample/htmx/petclinic/PetClinicHtmxPlaywrightTest.java
+++ b/viewers/webcomponents/sample-htmx-petclinic/src/playwright/java/org/apache/causeway/viewer/webcomponents/sample/htmx/petclinic/PetClinicHtmxPlaywrightTest.java
@@ -532,8 +532,32 @@ void propertyEditingAndPromptFocusRemainDeterministic() {
         assertThat(email.getAttribute("data-label-position")).isEqualTo("TOP");
         assertThat(page.locator("cw-property[id='emailAddress'] .causeway-property-description").textContent())
                 .isEqualTo("Email address used for appointment reminders.");
-        assertThat(page.locator("cw-property[id='lastVisit'] .causeway-property")
+        final var lastVisit = page.locator("cw-property[id='lastVisit']");
+        assertThat(lastVisit.locator(".causeway-property")
                 .getAttribute("data-label-position")).isEqualTo("TOP");
+        if (!nativeToolkit()) {
+            page.evaluate("() => { document.documentElement.lang = 'en-GB'; }");
+            lastVisit.locator("[data-causeway-action='edit']").click();
+            final var lastVisitEditorSelector = "cw-property[id='lastVisit'] [data-causeway-editor='lastVisit']";
+            final var lastVisitEditor = resolveEditor(lastVisitEditorSelector);
+            assertThat(lastVisitEditor.evaluate("element => element.inputElement?.value")).isEqualTo("12/08/2026");
+            assertThat(lastVisitEditor.evaluate("element => element.value")).isEqualTo("2026-08-12");
+            lastVisitEditor.focus();
+            page.keyboard().press("Tab");
+            assertThat(lastVisitEditor.evaluate(
+                    "element => element.shadowRoot?.activeElement?.hasAttribute('data-causeway-calendar-trigger')"))
+                    .as("Tab should move focus from the date input to its calendar trigger")
+                    .isEqualTo(true);
+            final var calendarTrigger = lastVisitEditor.locator("[data-causeway-calendar-trigger]");
+            assertThat(calendarTrigger.getAttribute("role")).isEqualTo("button");
+            assertThat(calendarTrigger.getAttribute("aria-label")).isEqualTo("Open Last Visit calendar");
+            page.keyboard().press("Enter");
+            page.waitForFunction("selector => document.querySelector(selector)?.opened === true", lastVisitEditorSelector);
+            assertThat(lastVisit.locator("[data-causeway-action='save']").count()).isEqualTo(1);
+            lastVisitEditor.evaluate("element => element.close()");
+            lastVisit.locator("[data-causeway-action='cancel']").click();
+            page.evaluate("() => { document.documentElement.lang = 'en'; }");
+        }
         final var knownAsEdit = knownAs.locator("[data-causeway-action='edit']");
         knownAsEdit.click();
         final var knownAsEditorSelector = "cw-property[id='knownAs'] [data-causeway-editor='knownAs']";