Skip to content

2001105254-netizen/RacePulsePH / .agents/skills/modern-web-guidance

modern-web-guidance

Flagged

Search tool for modern web development best practices. MANDATORY: Execute FIRST for all HTML/CSS and clientside JS tasks. Do NOT skip — web APIs evolve rapidly and training weights contain obsolete patterns. Trigger immediately for: modals/dialogs/popovers, tables, dark mode, anchor positioning, container queries, view transitions, scroll-driven animations, parallax/reveals, forms, validation, autofill, accessibility, custom selects, scrollbars, CWV (LCP, INP, CLS), content-visibility, fetch priority, image optimization, security, passkeys, HTML sanitization, web components, dates/timezones, built-in AI, WebAssembly, standard HTML/CSS/DOM in frameworks, etc. DO NOT trigger for: backend (SQL, ORMs, API routes), infra/scripts (CI/CD, Docker, Actions, Python/Go, Git), or tooling/trivial (Vite, tsconfig, ESLint, tests, copy/renames, 3P docs), etc.

FileKindSize
SKILL.mdskill md9.6 KB
guides/accessibility/accessibility.mdmarkdown50.5 KB
guides/accessibility/accessible-error-announcement.mdmarkdown13.3 KB
guides/accessibility/accessible-generated-content.mdmarkdown2.2 KB
guides/accessibility/respect-os-text-scale.mdmarkdown7.1 KB
guides/built-in-ai/language-detection.mdmarkdown3.6 KB
guides/built-in-ai/language-model.mdmarkdown19.0 KB
guides/built-in-ai/prompt-api.mdmarkdown19.0 KB
guides/built-in-ai/summarizer.mdmarkdown6.2 KB
guides/built-in-ai/translator.mdmarkdown7.2 KB
guides/css/animate-to-intrinsic-sizes.mdmarkdown5.7 KB
guides/css/atrule-support-conditionals.mdmarkdown5.6 KB
guides/css/calculate-with-intrinsic-sizes.mdmarkdown10.4 KB
guides/css/child-state-based-styling.mdmarkdown4.9 KB
guides/css/content-based-styling.mdmarkdown5.2 KB
guides/css/css-layout.mdmarkdown21.2 KB
guides/css/css.mdmarkdown12.3 KB
guides/css/design-token-reactivity.mdmarkdown5.8 KB
guides/css/dynamic-sibling-styling.mdmarkdown3.6 KB
guides/css/fluid-scaling.mdmarkdown3.2 KB
guides/css/individual-transform-properties.mdmarkdown3.6 KB
guides/css/overflow-clipping-control.mdmarkdown8.1 KB
guides/css/reduce-style-repetition.mdmarkdown3.9 KB
guides/css/responsive-design.mdmarkdown1.8 KB
guides/css/selector-atrule-combinations.mdmarkdown3.6 KB
guides/css/size-aware-styling.mdmarkdown2.9 KB
guides/css/style-parent-with-has.mdmarkdown13.6 KB
guides/css/usage-aware-component-variations.mdmarkdown5.1 KB
guides/forms/animated-select-picker.mdmarkdown8.5 KB
guides/forms/autofill-address-form.mdmarkdown4.9 KB
guides/forms/autofill-highlight-inputs.mdmarkdown3.5 KB
guides/forms/autofill-payment-form.mdmarkdown9.7 KB
guides/forms/autofill-sign-in-form.mdmarkdown10.5 KB
guides/forms/autofill-sign-up-form.mdmarkdown11.6 KB
guides/forms/brand-consistent-forms.mdmarkdown8.4 KB
guides/forms/branded-select-styling.mdmarkdown5.6 KB
guides/forms/custom-select-picker-layouts.mdmarkdown7.8 KB
guides/forms/form-fields-automatically-fit-contents.mdmarkdown5.9 KB
guides/forms/forms.mdmarkdown18.9 KB
guides/forms/ime-safe-enter-submit.mdmarkdown6.3 KB
guides/forms/required-field-feedback.mdmarkdown13.9 KB
guides/forms/rich-media-picker.mdmarkdown10.5 KB
guides/forms/select-menu-interaction.mdmarkdown12.9 KB
guides/forms/slider.mdmarkdown6.5 KB
guides/forms/sms-otp-form.mdmarkdown12.5 KB
guides/forms/switch.mdmarkdown2.5 KB
guides/forms/validate-input-after-interaction.mdmarkdown17.2 KB
guides/html/accessible-web-components.mdmarkdown5.1 KB
guides/html/custom-elements.mdmarkdown9.3 KB
guides/html/form-associated-custom-elements.mdmarkdown4.9 KB
guides/html/html.mdmarkdown20.8 KB
guides/html/prerendering-custom-elements.mdmarkdown3.6 KB
guides/html/shadow-dom.mdmarkdown3.8 KB
guides/html/styling-web-components.mdmarkdown8.7 KB
guides/html/web-components.mdmarkdown6.6 KB
guides/js/calculate-event-differentials.mdmarkdown8.3 KB
guides/js/capture-location-agnostic-data.mdmarkdown9.7 KB
guides/js/coordinate-global-events.mdmarkdown4.0 KB
guides/js/sort-high-precision-timestamps.mdmarkdown6.6 KB
guides/js/support-global-calendar-systems.mdmarkdown5.8 KB
guides/performance/batch-analytics-events.mdmarkdown6.4 KB
guides/performance/break-up-long-tasks.mdmarkdown2.2 KB
guides/performance/calculate-total-foreground-time.mdmarkdown2.9 KB
guides/performance/conditional-async-dependencies.mdmarkdown5.3 KB
guides/performance/defer-rendering-heavy-content.mdmarkdown6.3 KB
guides/performance/defer-work-until-scroll-ends.mdmarkdown3.3 KB
guides/performance/deliver-optimized-decorative-images.mdmarkdown2.8 KB
guides/performance/deprioritize-background-fetches.mdmarkdown1.8 KB
guides/performance/detect-initial-visibility-state.mdmarkdown4.6 KB
guides/performance/efficient-background-processing.mdmarkdown5.0 KB
guides/performance/faster-spa-view-transitions.mdmarkdown3.6 KB
guides/performance/flicker-free-client-side-ab-testing.mdmarkdown8.5 KB
guides/performance/full-session-analytics.mdmarkdown5.7 KB
guides/performance/identify-heavy-scripts.mdmarkdown4.2 KB
guides/performance/identify-inp-causes.mdmarkdown8.7 KB
guides/performance/improve-next-page-load-performance.mdmarkdown7.2 KB
guides/performance/interaction-paint-timing.mdmarkdown11.2 KB
guides/performance/interactions-in-complex-layouts.mdmarkdown3.4 KB
guides/performance/lazy-load-video-and-audio.mdmarkdown9.3 KB
guides/performance/optimize-image-priority.mdmarkdown4.5 KB
guides/performance/optimize-preload-priority.mdmarkdown3.3 KB
guides/performance/optimize-script-priority.mdmarkdown2.6 KB
guides/performance/out-of-order-html-streaming.mdmarkdown12.1 KB
guides/performance/performance.mdmarkdown20.6 KB
guides/performance/resolution-optimized-pseudo-elements.mdmarkdown2.3 KB
guides/performance/schedule-tasks-by-priority.mdmarkdown2.3 KB
guides/privacy/privacy.mdmarkdown11.0 KB
guides/pwa/install-web-app.mdmarkdown15.0 KB
guides/pwa/migrate-web-app-origin.mdmarkdown3.6 KB
guides/security/client-side-encryption.mdmarkdown14.8 KB
guides/security/digital-signatures.mdmarkdown9.9 KB
guides/security/local-network-access.mdmarkdown12.3 KB
guides/security/passkey-authentication.mdmarkdown11.5 KB
guides/security/passkey-conditional-create.mdmarkdown7.9 KB
guides/security/passkey-management.mdmarkdown17.3 KB
guides/security/passkey-reauthentication.mdmarkdown6.4 KB
guides/security/passkey-registration.mdmarkdown10.3 KB
guides/security/passkeys.mdmarkdown4.9 KB
guides/security/quick-sign-ins.mdmarkdown17.5 KB
guides/security/restrict-outbound-connections.mdmarkdown13.2 KB
guides/security/sanitize-untrusted-html.mdmarkdown5.6 KB
guides/security/secure-external-subresources.mdmarkdown14.5 KB
guides/security/security.mdmarkdown29.3 KB
guides/security/trusted-types.mdmarkdown7.3 KB
guides/security/validate-origins.mdmarkdown12.7 KB
guides/security/verify-email-ownership.mdmarkdown14.5 KB
guides/ui-atoms/carousel-slide-effects.mdmarkdown10.1 KB
guides/ui-atoms/component-specific-light-dark-theme.mdmarkdown9.5 KB
guides/ui-atoms/icons.mdmarkdown17.9 KB
guides/ui-atoms/position-aware-tooltips.mdmarkdown8.3 KB
guides/ui-atoms/pull-to-reveal.mdmarkdown5.0 KB
guides/ui-atoms/responsive-table.mdmarkdown4.4 KB
guides/ui-atoms/scroll-position-aware-elements.mdmarkdown3.6 KB
guides/ui-atoms/scroll-progress-indicator.mdmarkdown6.6 KB
guides/ui-atoms/scrollability-affordance-hints.mdmarkdown11.9 KB
guides/ui-atoms/shrinking-header-on-scroll.mdmarkdown7.0 KB
guides/ui-atoms/single-line-overflow.mdmarkdown16.1 KB
guides/ui-atoms/state-aware-sticky-headers.mdmarkdown6.7 KB
guides/ui-atoms/viewport-aware-dropdowns.mdmarkdown9.9 KB
guides/ui-behaviors/2d-panning.mdmarkdown9.2 KB
guides/ui-behaviors/anchor-positioning-tab-underline.mdmarkdown3.1 KB
guides/ui-behaviors/animate-element-entry-exit.mdmarkdown7.7 KB
guides/ui-behaviors/animate-to-from-top-layer.mdmarkdown10.7 KB
guides/ui-behaviors/carousel-snap-highlights.mdmarkdown7.5 KB
guides/ui-behaviors/consistent-cross-document-transitions.mdmarkdown13.9 KB
guides/ui-behaviors/cross-document-transitions.mdmarkdown4.4 KB
guides/ui-behaviors/custom-button-actions.mdmarkdown8.2 KB
guides/ui-behaviors/declarative-dialog-popover-control.mdmarkdown7.6 KB
guides/ui-behaviors/directional-navigation-transitions.mdmarkdown5.1 KB
guides/ui-behaviors/drag-and-drop.mdmarkdown16.4 KB
guides/ui-behaviors/drag.mdmarkdown6.8 KB
guides/ui-behaviors/dynamic-sibling-animations.mdmarkdown2.6 KB
guides/ui-behaviors/dynamic-sort.mdmarkdown6.9 KB
guides/ui-behaviors/group-element-transitions.mdmarkdown6.2 KB
guides/ui-behaviors/highlight-text-ranges.mdmarkdown6.4 KB
guides/ui-behaviors/interactive-content-reveal.mdmarkdown5.7 KB
guides/ui-behaviors/interest-triggered-action-previews.mdmarkdown4.9 KB
guides/ui-behaviors/interest-triggered-tooltips.mdmarkdown19.8 KB
guides/ui-behaviors/light-dismiss-a-dialog.mdmarkdown4.1 KB
guides/ui-behaviors/motion.mdmarkdown7.6 KB
guides/ui-behaviors/move-dom-element-without-losing-state.mdmarkdown3.8 KB
guides/ui-behaviors/parallax-scroll-effects.mdmarkdown9.5 KB
guides/ui-behaviors/persistent-top-layer-ui.mdmarkdown2.3 KB
guides/ui-behaviors/physics-based-easing.mdmarkdown5.8 KB
guides/ui-behaviors/platform-controls-dismiss-dialog.mdmarkdown2.6 KB
guides/ui-behaviors/prevent-page-scroll-under-modal-dialog.mdmarkdown5.0 KB
guides/ui-behaviors/same-document-transitions.mdmarkdown8.3 KB
guides/ui-behaviors/scoped-component-transitions.mdmarkdown11.7 KB
guides/ui-behaviors/scroll-completion-effects.mdmarkdown7.5 KB
guides/ui-behaviors/scroll-entry-exit-effects.mdmarkdown9.8 KB
guides/ui-behaviors/scroll-snap-realtime-feedback.mdmarkdown10.7 KB
guides/ui-behaviors/scroll-snap-state-sync.mdmarkdown4.8 KB
guides/ui-behaviors/scroll-target-on-load.mdmarkdown3.4 KB
guides/ui-behaviors/scrollytelling.mdmarkdown8.8 KB
guides/ui-behaviors/search-hidden-content.mdmarkdown6.8 KB
guides/ui-behaviors/sortable-table.mdmarkdown7.7 KB
guides/ui-behaviors/spatial-navigation.mdmarkdown6.8 KB
guides/ui-behaviors/swipe-to-remove.mdmarkdown33.9 KB
guides/ui-behaviors/swipe-to-reveal.mdmarkdown14.2 KB
guides/ui-components/accordion.mdmarkdown14.7 KB
guides/ui-components/app-menus.mdmarkdown15.7 KB
guides/ui-components/breadcrumbs.mdmarkdown12.3 KB
guides/ui-components/card.mdmarkdown8.2 KB
guides/ui-components/carousel.mdmarkdown15.1 KB
guides/ui-components/checkbox.mdmarkdown5.7 KB
guides/ui-components/copy-button.mdmarkdown14.5 KB
guides/ui-components/dark-mode-toggle.mdmarkdown9.2 KB
guides/ui-components/dialog.mdmarkdown12.1 KB
guides/ui-components/hovercard.mdmarkdown20.9 KB
guides/ui-components/menu.mdmarkdown31.1 KB
guides/ui-components/navbar.mdmarkdown17.8 KB
guides/ui-components/navigation-drawer.mdmarkdown20.3 KB
guides/ui-components/persistent-app-tours.mdmarkdown11.2 KB
guides/ui-components/persistent-toast-notifications.mdmarkdown13.8 KB
guides/ui-components/progress-ring.mdmarkdown6.9 KB
guides/ui-components/progress.mdmarkdown10.6 KB
guides/ui-components/scrollspy.mdmarkdown6.9 KB
guides/ui-components/spinner.mdmarkdown5.9 KB
guides/ui-components/stack-drill-down.mdmarkdown36.5 KB
guides/ui-components/tabs.mdmarkdown21.7 KB
guides/ui-components/toolbar.mdmarkdown21.5 KB
guides/user-experience/content-first-noise-reduction.mdmarkdown8.3 KB
guides/user-experience/form-factor-adaptation.mdmarkdown6.0 KB
guides/user-experience/natural-interactions.mdmarkdown9.7 KB
guides/visual-design/adapt-scrollbar-to-contrast-preferences.mdmarkdown3.6 KB
guides/visual-design/apply-webgl-shaders.mdmarkdown13.1 KB
guides/visual-design/browser-ui-theming.mdmarkdown4.1 KB
guides/visual-design/color.mdmarkdown4.4 KB
guides/visual-design/complex-shapes.mdmarkdown3.5 KB
guides/visual-design/contrast-color.mdmarkdown7.1 KB
guides/visual-design/custom-text-decorations.mdmarkdown16.4 KB
guides/visual-design/customize-scrollbar-color-and-thickness.mdmarkdown2.7 KB
guides/visual-design/dark-mode.mdmarkdown16.8 KB
guides/visual-design/equal-width-text-lines.mdmarkdown6.4 KB
guides/visual-design/export-html-media-from-canvas.mdmarkdown17.1 KB
guides/visual-design/expose-canvas-content-to-browser-features.mdmarkdown19.6 KB
guides/visual-design/improve-text-layout-and-legibility.mdmarkdown5.1 KB
guides/visual-design/interactive-content-in-3d-scenes.mdmarkdown19.2 KB
guides/visual-design/precise-text-alignment.mdmarkdown4.8 KB
guides/visual-design/shaped-cutouts.mdmarkdown7.1 KB

guides/accessibility/accessible-error-announcement.md

View on GitHub
# Accessible Error Announcement

## The Problem
Standard HTML5 validation provides visual feedback (via `:invalid` or `:user-invalid`), but it doesn't automatically synchronize with accessibility attributes like `aria-invalid`. 

If you use standard `:invalid` styling, screen readers might announce "Invalid entry" the moment a user tabs into a required field that is currently empty. This creates a disruptive experience for users using assistive technologies, as the error is announced before interaction has occurred.

## The Solution
We want the *programmatic* state (`aria-invalid="true"`) to be applied **at the exact same moment** the *visual* state (`:user-invalid`) applies. Since `:user-invalid` relies on the browser's internal "user-interacted" flag, we can use JavaScript to check that this selector matches during standard interaction events.

Set `aria-invalid="false"` until `:user-invalid` matches, rather than leaving the attribute unset. Firefox and Safari expose an empty `required` field as invalid from page load, so an unset attribute still causes the premature "invalid entry" announcement there.

### Implementation Strategy

1.  **Visual Layer**: Use CSS `:user-invalid` to show borders/icons.
2.  **Accessibility Layer**: Use `aria-invalid`, and list the error message in `aria-describedby` while the field is invalid, to communicate state to Assistive Technology (AT). Announce an error that appears when the user leaves a field through one polite live region for the page.
3.  **Bridge Visual & Accessibility Layer**: Create a lightweight JavaScript utility that listens for `blur`, `change`, `input` and `invalid` events, checks if the element matches `:user-invalid`, and updates the ARIA attributes accordingly.
4.  **Focus on Submit**: Screen readers announce a field's error when focus reaches the field, so after a failed submit, move focus to the first invalid field, or to an error summary (a heading followed by a link to each invalid field) on a long form. Native validation moves focus to the first invalid field for you; if the form uses `novalidate`, move it in your submit handler.

## Implementation Guide

### 1. HTML Structure
Link your input to its error message by setting the input's `data-error` attribute to the error message's `id`. The script in section 3 lists that `id` in `aria-describedby` only while the field is invalid. Don't reference the error from `aria-describedby` in the markup: the error element is always in the page, and text that `aria-describedby` references is announced even when it's hidden, so the error would be read out before the user has interacted.

```html
<form>
  <div class="field">
    <label for="email">Email</label>
    <input 
      type="email" 
      id="email" 
      required 
      data-error="email-error"
    >
    <span id="email-error" class="error-msg">
      Please enter a valid email address.
    </span>
  </div>
</form>
```

### 2. CSS
Control the visibility of the error message using the native pseudo-class `:user-invalid`.

```css
.error-msg {
  display: none;
  color: #d93025;
}

/* Show error message when input is user-invalid */
input:user-invalid ~ .error-msg {
  display: block;
}

/* Optional: Visual cues on the input itself */
input:user-invalid {
  border-color: #d93025;
}
```

### 3. JavaScript
Since there is no "UserInvalidChanged" event, hook into standard form events to check the state.

Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:

* Set `aria-invalid="false"` until `:user-invalid` matches, rather than leaving it unset. Firefox and Safari expose an empty `required` field as invalid from page load, and Chromium doesn't expose an empty `required` field as invalid after interaction unless `aria-invalid="true"` is set.
* Link each field to its error message by setting the field's `data-error` attribute to the error message's `id` (`data-error="email-error"` for `<div id="email-error">`), and let the script list that `id` in `aria-describedby` only while the field is invalid. Don't reference the error from `aria-describedby` in the markup: the error element is always in the page, and text that `aria-describedby` references is announced even when it's hidden.
* Announce an error that appears when the user leaves or changes a field through one polite live region for the page, a moment later so it doesn't talk over the next field. Don't make each error message a live region: a live region that is shown, rather than changed, isn't announced reliably. After a failed submit, move focus to the first invalid field so that its error is announced instead.

```javascript
// List the field's error message (the id in data-error) in aria-describedby only while
// it's shown: text that aria-describedby references is announced even when it's hidden.
const linkError = (el, shown) => {
  const errorId = el.dataset.error;
  if (!errorId) return;
  const ids = (el.getAttribute('aria-describedby') || '').split(/\s+/).filter((id) => id && id !== errorId);
  if (shown) ids.push(errorId);
  if (ids.length) el.setAttribute('aria-describedby', ids.join(' '));
  else el.removeAttribute('aria-describedby');
};

// One polite live region for the page announces an error that appears when the user
// leaves or changes a field. Run this once the form is in the page.
const announcer = document.createElement('div');
announcer.setAttribute('aria-live', 'polite');
announcer.classList.add('visually-hidden');
document.body.append(announcer);
let announceTimer;
let announcedField;

// Text as a screen reader reads it: icons' text alternatives in, aria-hidden text out.
const spokenText = (node) => {
  const copy = node.cloneNode(true);
  copy.querySelectorAll('[aria-hidden="true"]').forEach((n) => n.remove());
  copy.querySelectorAll('[role="img"][aria-label]').forEach((n) => n.replaceWith(`${n.getAttribute('aria-label')}: `));
  return copy.textContent.replace(/\s+/g, ' ').trim();
};
const announceError = (el) => {
  const error = document.getElementById(el.dataset.error);
  if (!error) return;
  const label = el.labels?.[0] ? `${spokenText(el.labels[0])}: ` : '';
  clearTimeout(announceTimer);
  announcer.textContent = '';
  announcedField = el;
  // Wait until the screen reader has announced the field that receives focus next.
  announceTimer = setTimeout(() => { announcer.textContent = label + spokenText(error); }, 500);
};

// Sync aria-invalid with the CSS :user-invalid state. Only form fields are synced, and
// an aria-invalid="true" that this script didn't set (for example from a server check)
// is left alone.
const flagged = new WeakSet();
// Fields whose current error has been announced, or read out by focus after a failed
// submit. A field can become invalid while the user types, so this is tracked separately.
const announced = new WeakSet();
const syncAria = (el, announce = false) => {
  if (!el.matches?.('input, select, textarea')) return;
  const invalid = el.matches(':user-invalid');
  if (invalid) {
    if (announce && !announced.has(el)) {
      announceError(el);
      announced.add(el);
    }
    el.setAttribute('aria-invalid', 'true');
    linkError(el, true);
    flagged.add(el);
  } else if (flagged.has(el) || el.getAttribute('aria-invalid') !== 'true') {
    el.setAttribute('aria-invalid', 'false');
    linkError(el, false);
    flagged.delete(el);
    announced.delete(el);
    // Clear a fixed field's announcement so it isn't found later when reading the page.
    if (announcedField === el) {
      clearTimeout(announceTimer);
      announcer.textContent = '';
    }
  }
};

// Start every field at aria-invalid="false".
document.querySelectorAll('input, select, textarea').forEach((el) => syncAria(el));

// Update on blur (to show and announce an error) and input (to clear it)
document.addEventListener('blur', (e) => syncAria(e.target, true), true);
document.addEventListener('input', (e) => {
  if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);
});

// Checkboxes, radio buttons and other controls that commit on 'change' can become
// :user-invalid without losing focus, so update on change too.
document.addEventListener('change', (e) => syncAria(e.target, true), true);

// A failed submit fires 'invalid' on each failing field, including required fields the
// user never touched, so update those too. 'invalid' doesn't bubble. Focus moving to the
// first invalid field announces its error, so these aren't announced.
document.addEventListener('invalid', (e) => {
  announced.add(e.target);
  syncAria(e.target);
}, true);

// Reset clears :user-invalid after the 'reset' event, so update each field afterwards.
document.addEventListener('reset', (e) => {
  setTimeout(() => [...e.target.elements].forEach((el) => syncAria(el)));
}, true);
```

Hide the live region with the `.visually-hidden` utility:

```css
/* Hides content visually but keeps it in the accessibility tree */
.visually-hidden:where(:not(:focus-within, :active)) {
  position: absolute !important;
  clip-path: inset(50%) !important;
  overflow: hidden !important;
  width: 1px !important;
  height: 1px !important;
  margin: -1px !important;
  padding: 0 !important;
  border: 0 !important;
  white-space: nowrap !important;
}
```

## Fallbacking & Browser Support

### Fallbacks & browser support for :user-valid and :user-invalid

Baseline status for :user-valid and :user-invalid: Widely available. It's been Baseline since 2023-11-02.
Supported by: Chrome 119 (Oct 2023), Edge 119 (Nov 2023), Firefox 88 (Apr 2021), and Safari 16.5 (May 2023).

### CSS for Fallback

```css
/* Applies to every field that can be invalid (input, select, textarea). :is() keeps the
   rule working where :user-invalid isn't supported: in a plain selector list, one
   unsupported selector drops the whole rule. */
:is(:user-invalid, .user-invalid-fallback) {
  border-color: #d93025;
  background-color: #fce8e6;
}

:is(:user-invalid, .user-invalid-fallback) + .error-msg {
  display: block;
}
```

### JavaScript Fallback

Use a reusable utility that tracks interaction state using a `WeakMap`. This avoids polluting the DOM with "dirty" classes or data attributes.

```javascript
const UserInvalidFallback = (() => {
  const dirtyState = new WeakMap();

  const updateState = (input) => {
    // validity.valid gives the current state without firing an 'invalid' event, as checkValidity() does.
    const isValid = input.validity.valid;

    // Update both visual and ARIA state
    input.classList.toggle('user-invalid-fallback', !isValid);
    input.classList.toggle('user-valid-fallback', isValid);

    input.setAttribute('aria-invalid', isValid ? 'false' : 'true');
    linkError(input, !isValid);
  };

  // List the error message (the id in data-error) in aria-describedby only while it's
  // shown: text that aria-describedby references is announced even when it's hidden.
  const linkError = (input, shown) => {
    const errorId = input.dataset.error;
    if (!errorId) return;
    const ids = (input.getAttribute('aria-describedby') || '').split(/\s+/).filter((id) => id && id !== errorId);
    if (shown) ids.push(errorId);
    if (ids.length) input.setAttribute('aria-describedby', ids.join(' '));
    else input.removeAttribute('aria-describedby');
  };

  const handleEvent = (event) => {
    const input = event.target;

    if (event.type === 'reset') {
      const controls = input.elements || [];
      for (const control of controls) {
        dirtyState.delete(control);
        control.classList.remove('user-invalid-fallback');
        control.classList.remove('user-valid-fallback');
        if (control.matches('input, select, textarea')) control.setAttribute('aria-invalid', 'false');
        if (control.dataset?.error) linkError(control, false);
      }
      return;
    }

    if (!input.checkValidity) return;

    // A submit attempt counts as interaction: the browser fires 'invalid' on each failing
    // field, including required fields the user never touched, so flag them all.
    if (event.type === 'invalid') {
      dirtyState.set(input, { hasInteracted: true, hasBlurred: true });
      updateState(input);
      return;
    }

    if (event.type === 'input' || event.type === 'change') {
      const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };
      state.hasInteracted = true;
      dirtyState.set(input, state);
      if (state.hasBlurred) {
        updateState(input);
      }
    } else if (event.type === 'blur') {
      const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };
      state.hasBlurred = true;
      dirtyState.set(input, state);
      if (state.hasInteracted) {
        updateState(input);
      }
    }
  };

  const init = (root = document) => {
    if (CSS.supports('selector(:user-invalid)')) return;

    // Firefox and Safari expose an empty required field as invalid from page load.
    root.querySelectorAll('input, select, textarea').forEach((el) => {
      if (!el.hasAttribute('aria-invalid')) el.setAttribute('aria-invalid', 'false');
    });

    root.addEventListener('blur', handleEvent, true); // Capture phase
    root.addEventListener('input', handleEvent);
    root.addEventListener('change', handleEvent);
    root.addEventListener('invalid', handleEvent, true); // invalid doesn't bubble
    root.addEventListener('reset', handleEvent, true); // Capture resets
  };

  return { init };
})();

// Initialize for a specific form
const form = document.querySelector('#demo-form');
UserInvalidFallback.init(form);
```
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall