Skip to content

fix(forms): improve aria attribute management#128

Open
coryrylan wants to merge 1 commit into
mainfrom
topic-cleanup-forms
Open

fix(forms): improve aria attribute management#128
coryrylan wants to merge 1 commit into
mainfrom
topic-cleanup-forms

Conversation

@coryrylan

@coryrylan coryrylan commented Jun 9, 2026

Copy link
Copy Markdown
Collaborator
  • Modified state controllers to correctly manage aria attributes when values are null or undefined.
  • Improved test cases for state controllers to ensure proper aria attribute handling.
  • Introduced custom slider defaults in tests to validate default behavior.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed form controls to properly handle null and undefined state values in accessibility attributes (current, expanded, pressed, selected).
    • Fixed form data submission to correctly exclude disabled checkbox values.
    • Changed invalid numeric input handling from throwing errors to emitting console warnings.
  • New Features

    • Added support for custom slider default values configuration.

- Modified state controllers to correctly manage aria attributes when values are null or undefined.
- Improved test cases for state controllers to ensure proper aria attribute handling.
- Introduced custom slider defaults in tests to validate default behavior.

Signed-off-by: Cory Rylan <crylan@nvidia.com>
@coryrylan coryrylan requested a review from johnyanarella June 9, 2026 01:48
@coryrylan coryrylan self-assigned this Jun 9, 2026
@coderabbitai

coderabbitai Bot commented Jun 9, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The PR refactors aria attribute handling across state controllers to consistently set internals to null for absent or readonly states, exports FormControlInstance type for validator contracts, updates validators and the control mixin to use concrete instance typing instead of generic casts, and adds test coverage for disabled form submission and custom slider defaults.

Changes

State Controllers and Type System Refactoring

Layer / File(s) Summary
State controllers aria attribute handling
projects/forms/src/internal/controllers/state-current.controller.ts, state-expanded.controller.ts, state-pressed.controller.ts, state-selected.controller.ts, projects/forms/src/internal/controllers/state-*.controller.test.ts
Four state controllers now consistently set aria internals to null when host values are absent or readonly, replacing conditional skip logic. Anchor aria-current now derives from host.current ?? 'page'. Tests verify null assertions and aria-current preservation.
Type exports and validator signatures
projects/forms/src/internal/types.ts, projects/forms/src/validators/index.ts, projects/forms/src/validators/index.test.ts
FormControlInstance is exported from types; Validator type and both validator implementations (requiredValidator, valueSchemaValidator) now use FormControlInstance for the element parameter instead of FormControl, removing prior any-typed casts.
Control mixin typing and error handling
projects/forms/src/mixins/control.ts, projects/forms/src/mixins/control.test.ts
Type imports reformatted to multi-line; valueAsNumber setter now warns instead of throws on non-number values; validator invocation passes this typed as FormControlInstance. Tests add afterEach mock restoration.
Feature test coverage
projects/forms/src/mixins/checkbox.test.ts, projects/forms/src/mixins/slider.test.ts
Checkbox test adds verification that FormData excludes the value when the element is disabled and restores it when re-enabled. Slider test adds custom defaults validation: bounds, aria values, form submission, and reset behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

scope(forms), scope(internals)

Suggested reviewers

  • johnyanarella
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix(forms): improve aria attribute management' accurately summarizes the main change: refactoring aria attribute handling across form state controllers to correctly manage null/undefined values.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch topic-cleanup-forms

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
projects/forms/src/mixins/control.ts (1)

443-449: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Breaking change: valueAsNumber now warns instead of throwing.

The valueAsNumber setter behavior changed from throwing a FormControlError to emitting a console.warn when attempting to set a number value on a non-number-typed control. This reduces strictness and could mask programming errors where code incorrectly attempts numeric assignment on string-typed controls.

Additionally, the JSDoc comment for valueAsNumber (lines 156-159) does not document this warning behavior or the conditions under which it occurs.

📝 Suggested JSDoc enhancement
   /**
    * The current value parsed as a number.
+   * 
+   * `@remarks`
+   * Setting this property on a non-number-typed control will log a warning and no-op.
    */
   valueAsNumber: number;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@projects/forms/src/mixins/control.ts` around lines 443 - 449, The setter
valueAsNumber in the FormControl mixin (method: set valueAsNumber) currently
calls console.warn on type mismatch; revert it to throw a FormControlError when
attempting to set a numeric value on a non-number-typed control to restore
previous strict behavior, and update the JSDoc for valueAsNumber to document
that it throws FormControlError when the underlying generic type is not number
and describe the exact condition checked (typeof this._value !== 'number' ||
typeof value !== 'number'). Locate set valueAsNumber and the JSDoc block for
valueAsNumber and replace the console.warn path with: throw new
FormControlError(this.localName, 'cannot set number value on non-number type'),
and expand the JSDoc to state the throwing behavior and the condition under
which it will throw.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@projects/forms/src/mixins/slider.test.ts`:
- Around line 72-97: The test's fixture cleanup can leak when an assertion fails
because removeFixture(customFixture) is only called at the end; wrap the async
test body so that after awaiting createFixture(...) and assigning customFixture
you run your assertions inside a try block and call removeFixture(customFixture)
in a finally block (so the fixture is always removed). Locate the test named
"should support custom slider defaults" and modify the structure around
createFixture, customFixture, and removeFixture to ensure
removeFixture(customFixture) executes in finally; keep existing assertions and
operations on customElement (min, max, step, value, getInternals checks,
FormData check, valueAsNumber change and formResetCallback) inside the try.
- Around line 23-40: CustomSliderDefaultsTestElement (which extends
SliderFormControlMixin<typeof HTMLElement>(HTMLElement)) is missing a
requestUpdate method stub like SliderTestElement has, so any mixin calls to
requestUpdate (e.g., when setting valueAsNumber) can throw; add a minimal
requestUpdate(): Promise<void> stub to CustomSliderDefaultsTestElement that
returns Promise.resolve() (or mirrors the signature used by the mixin) so the
mixin’s calls to requestUpdate succeed during tests.

---

Outside diff comments:
In `@projects/forms/src/mixins/control.ts`:
- Around line 443-449: The setter valueAsNumber in the FormControl mixin
(method: set valueAsNumber) currently calls console.warn on type mismatch;
revert it to throw a FormControlError when attempting to set a numeric value on
a non-number-typed control to restore previous strict behavior, and update the
JSDoc for valueAsNumber to document that it throws FormControlError when the
underlying generic type is not number and describe the exact condition checked
(typeof this._value !== 'number' || typeof value !== 'number'). Locate set
valueAsNumber and the JSDoc block for valueAsNumber and replace the console.warn
path with: throw new FormControlError(this.localName, 'cannot set number value
on non-number type'), and expand the JSDoc to state the throwing behavior and
the condition under which it will throw.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Enterprise

Run ID: 79040383-af17-4367-84a4-e197e77912eb

📥 Commits

Reviewing files that changed from the base of the PR and between 686ff96 and d03d352.

📒 Files selected for processing (15)
  • projects/forms/src/internal/controllers/state-current.controller.test.ts
  • projects/forms/src/internal/controllers/state-current.controller.ts
  • projects/forms/src/internal/controllers/state-expanded.controller.test.ts
  • projects/forms/src/internal/controllers/state-expanded.controller.ts
  • projects/forms/src/internal/controllers/state-pressed.controller.test.ts
  • projects/forms/src/internal/controllers/state-pressed.controller.ts
  • projects/forms/src/internal/controllers/state-selected.controller.test.ts
  • projects/forms/src/internal/controllers/state-selected.controller.ts
  • projects/forms/src/internal/types.ts
  • projects/forms/src/mixins/checkbox.test.ts
  • projects/forms/src/mixins/control.test.ts
  • projects/forms/src/mixins/control.ts
  • projects/forms/src/mixins/slider.test.ts
  • projects/forms/src/validators/index.test.ts
  • projects/forms/src/validators/index.ts

Comment thread projects/forms/src/mixins/slider.test.ts
Comment on lines +72 to +97
it('should support custom slider defaults', async () => {
const customFixture = await createFixture(html`
<form>
<ui-custom-slider-defaults-test-element name="level"></ui-custom-slider-defaults-test-element>
</form>
`);
const customElement = customFixture.querySelector<CustomSliderDefaultsTestElement>(
'ui-custom-slider-defaults-test-element'
)!;
const customForm = customFixture.querySelector<HTMLFormElement>('form')!;

expect(customElement.min).toBe(10);
expect(customElement.max).toBe(20);
expect(customElement.step).toBe(2);
expect(customElement.value).toBe(14);
expect(getInternals(customElement).ariaValueMin).toBe('10');
expect(getInternals(customElement).ariaValueMax).toBe('20');
expect(getInternals(customElement).ariaValueNow).toBe('14');
expect(new FormData(customForm).get('level')).toBe('14');

customElement.valueAsNumber = 18;
customElement.formResetCallback();
expect(customElement.valueAsNumber).toBe(14);

removeFixture(customFixture);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Guard fixture cleanup with try/finally in the async test.

If any assertion fails before Line 96, customFixture is never removed, which can leak DOM state into later tests.

As per coding guidelines, tests should follow stable fixture lifecycle patterns from /projects/site/src/docs/internal/guidelines/testing-unit.md (including reliable fixture handling).

Proposed fix
   it('should support custom slider defaults', async () => {
     const customFixture = await createFixture(html`
       <form>
         <ui-custom-slider-defaults-test-element name="level"></ui-custom-slider-defaults-test-element>
       </form>
     `);
-    const customElement = customFixture.querySelector<CustomSliderDefaultsTestElement>(
-      'ui-custom-slider-defaults-test-element'
-    )!;
-    const customForm = customFixture.querySelector<HTMLFormElement>('form')!;
-
-    expect(customElement.min).toBe(10);
-    expect(customElement.max).toBe(20);
-    expect(customElement.step).toBe(2);
-    expect(customElement.value).toBe(14);
-    expect(getInternals(customElement).ariaValueMin).toBe('10');
-    expect(getInternals(customElement).ariaValueMax).toBe('20');
-    expect(getInternals(customElement).ariaValueNow).toBe('14');
-    expect(new FormData(customForm).get('level')).toBe('14');
-
-    customElement.valueAsNumber = 18;
-    customElement.formResetCallback();
-    expect(customElement.valueAsNumber).toBe(14);
-
-    removeFixture(customFixture);
+    try {
+      const customElement = customFixture.querySelector<CustomSliderDefaultsTestElement>(
+        'ui-custom-slider-defaults-test-element'
+      )!;
+      const customForm = customFixture.querySelector<HTMLFormElement>('form')!;
+
+      expect(customElement.min).toBe(10);
+      expect(customElement.max).toBe(20);
+      expect(customElement.step).toBe(2);
+      expect(customElement.value).toBe(14);
+      expect(getInternals(customElement).ariaValueMin).toBe('10');
+      expect(getInternals(customElement).ariaValueMax).toBe('20');
+      expect(getInternals(customElement).ariaValueNow).toBe('14');
+      expect(new FormData(customForm).get('level')).toBe('14');
+
+      customElement.valueAsNumber = 18;
+      customElement.formResetCallback();
+      expect(customElement.valueAsNumber).toBe(14);
+    } finally {
+      removeFixture(customFixture);
+    }
   });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('should support custom slider defaults', async () => {
const customFixture = await createFixture(html`
<form>
<ui-custom-slider-defaults-test-element name="level"></ui-custom-slider-defaults-test-element>
</form>
`);
const customElement = customFixture.querySelector<CustomSliderDefaultsTestElement>(
'ui-custom-slider-defaults-test-element'
)!;
const customForm = customFixture.querySelector<HTMLFormElement>('form')!;
expect(customElement.min).toBe(10);
expect(customElement.max).toBe(20);
expect(customElement.step).toBe(2);
expect(customElement.value).toBe(14);
expect(getInternals(customElement).ariaValueMin).toBe('10');
expect(getInternals(customElement).ariaValueMax).toBe('20');
expect(getInternals(customElement).ariaValueNow).toBe('14');
expect(new FormData(customForm).get('level')).toBe('14');
customElement.valueAsNumber = 18;
customElement.formResetCallback();
expect(customElement.valueAsNumber).toBe(14);
removeFixture(customFixture);
});
it('should support custom slider defaults', async () => {
const customFixture = await createFixture(html`
<form>
<ui-custom-slider-defaults-test-element name="level"></ui-custom-slider-defaults-test-element>
</form>
`);
try {
const customElement = customFixture.querySelector<CustomSliderDefaultsTestElement>(
'ui-custom-slider-defaults-test-element'
)!;
const customForm = customFixture.querySelector<HTMLFormElement>('form')!;
expect(customElement.min).toBe(10);
expect(customElement.max).toBe(20);
expect(customElement.step).toBe(2);
expect(customElement.value).toBe(14);
expect(getInternals(customElement).ariaValueMin).toBe('10');
expect(getInternals(customElement).ariaValueMax).toBe('20');
expect(getInternals(customElement).ariaValueNow).toBe('14');
expect(new FormData(customForm).get('level')).toBe('14');
customElement.valueAsNumber = 18;
customElement.formResetCallback();
expect(customElement.valueAsNumber).toBe(14);
} finally {
removeFixture(customFixture);
}
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@projects/forms/src/mixins/slider.test.ts` around lines 72 - 97, The test's
fixture cleanup can leak when an assertion fails because
removeFixture(customFixture) is only called at the end; wrap the async test body
so that after awaiting createFixture(...) and assigning customFixture you run
your assertions inside a try block and call removeFixture(customFixture) in a
finally block (so the fixture is always removed). Locate the test named "should
support custom slider defaults" and modify the structure around createFixture,
customFixture, and removeFixture to ensure removeFixture(customFixture) executes
in finally; keep existing assertions and operations on customElement (min, max,
step, value, getInternals checks, FormData check, valueAsNumber change and
formResetCallback) inside the try.

Source: Coding guidelines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant