From 21b4d05d31b0e16ae9acff71f56f8af86ea175e5 Mon Sep 17 00:00:00 2001 From: michael faith Date: Fri, 20 Dec 2024 16:38:23 -0600 Subject: [PATCH] feat(label-has-associated-control): add option for enforcing label's htmlFor matches control's id This change adds an option to the `label-has-associated-control` rule, enforcing that the label's htmlFor attribute matches the associated control's id attribute. Previously, the only validation done on htmlFor was that it was on the label component and had text. There was no attempt to cross-check that value against any attribute on the associated control. Not, when the option is enabled, cases where they don't match will report. I also took the opportunity to update the error messages so that each assert type gets an error message with verbiage specific to the assertion. (not sure if this should be called out as a separate feature in the changelog?). Note: the current implementation only checks the first instance it finds of child component that matches each control component type. It assumes that there won't be any acceptable cases where a label would have multiple inputs nested beneath it. Let me know if that assumption doesn't hold. Closes: --- .../label-has-associated-control-test.js | 33 +++ __tests__/src/util/getChildComponent-test.js | 224 ++++++++++++++++++ docs/rules/label-has-associated-control.md | 42 ++-- src/rules/label-has-associated-control.js | 85 ++++++- src/util/getChildComponent.js | 50 ++++ src/util/mayContainChildComponent.js | 43 +--- 6 files changed, 415 insertions(+), 62 deletions(-) create mode 100644 __tests__/src/util/getChildComponent-test.js create mode 100644 src/util/getChildComponent.js diff --git a/__tests__/src/rules/label-has-associated-control-test.js b/__tests__/src/rules/label-has-associated-control-test.js index 01d02e06..ad82c424 100644 --- a/__tests__/src/rules/label-has-associated-control-test.js +++ b/__tests__/src/rules/label-has-associated-control-test.js @@ -27,6 +27,7 @@ const errorMessages = { nesting: 'A form label must have an associated control as a descendant.', either: 'A form label must either have a valid htmlFor attribute or a control as a descendant.', both: 'A form label must have a valid htmlFor attribute and a control as a descendant.', + htmlForShouldMatchId: 'A form label must have a htmlFor attribute that matches the id of the associated control.', }; const expectedErrors = {}; Object.keys(errorMessages).forEach((key) => { @@ -58,6 +59,7 @@ const htmlForValid = [ { code: '