@aarongustafson/form-show-if 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Aaron Gustafson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,180 @@
1
+ # Show If Web Component
2
+
3
+ Currently, HTML provides no mechanism to show & hide dependent fields. Sometimes you only want a field to show when certain other fields have a (particular) value. The `form-show-if` web component enables that.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @aarongustafson/form-show-if
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Option 1: Auto-define the custom element (easiest)
14
+
15
+ Import the package to automatically define the `<form-show-if>` custom element:
16
+
17
+ ```javascript
18
+ import '@aarongustafson/form-show-if';
19
+ ```
20
+
21
+ Or use the define-only script in HTML:
22
+
23
+ ```html
24
+ <script src="./node_modules/@aarongustafson/form-show-if/define.js" type="module"></script>
25
+ ```
26
+
27
+ ### Option 2: Import the class and define manually
28
+
29
+ Import the class and define the custom element with your preferred tag name:
30
+
31
+ ```javascript
32
+ import { FormShowIfElement } from '@aarongustafson/form-show-if/form-show-if.js';
33
+
34
+ // Define with default name
35
+ customElements.define('form-show-if', FormShowIfElement);
36
+
37
+ // Or define with a custom name
38
+ customElements.define('my-conditional-field', FormShowIfElement);
39
+ ```
40
+
41
+ ### Option 3: Import everything (class + auto-define)
42
+
43
+ Get both the class export and automatic element definition:
44
+
45
+ ```javascript
46
+ import { FormShowIfElement } from '@aarongustafson/form-show-if';
47
+ // The custom element is now defined AND you have access to the class
48
+ ```
49
+
50
+ ### CDN Usage
51
+
52
+ You can also use the component directly from a CDN:
53
+
54
+ ```html
55
+ <script src="https://unpkg.com/@aarongustafson/form-show-if/define.js" type="module"></script>
56
+ ```
57
+
58
+ ## API
59
+
60
+ <ul>
61
+ <li><code>conditions</code><br> A double pipe (||) separated list of <code>name</code>/<code>value</code> pairs. When fields with the provided <code>name</code> values are updated, the value of those fields will be compared against the values you provided (or * for anything). If any resolve to true, the field will be shown, otherwise it will be hidden.</li>
62
+ <li><code>disabled-class</code> (optional)<br> By default the field & <code>label</code> wrapper will be marked <code>hidden</code> when disabled, but you can apply a custom <code>class</code> to be used instead, when the field is disabled.</li>
63
+ <li><code>enabled-class</code> (optional)<br> By default the field & <code>label</code> wrapper will not be <code>hidden</code> when enabled, but you can apply a custom <code>class</code> to the wrapper, when the field is enabled.</li>
64
+ </ul>
65
+
66
+ ## Markup Assumptions
67
+
68
+ This web component assumes the fields you reference in `conditions` exist in the DOM when the component is loaded. If they don't, they will be ignored.
69
+
70
+ ## Implementation notes
71
+
72
+ The "wrapper" mentioned below refers to the nearest mutual parent of the field & its label. It may be the `form-show-if` element itself.
73
+
74
+ 1. **Field markup changes.** When the field is hidden (conditions not met), it will receive the `disabled` attribute and all fields within the wrapper are disabled.
75
+
76
+ 2. **Visual state management.** If `disabled-class` and/or `enabled-class` **are not** defined:
77
+ * When **no** condition is met: The wrapper has a `hidden` attribute
78
+ * When **any** condition is met: The `hidden` attribute is removed from the wrapper
79
+
80
+ 3. **Custom class management.** If `disabled-class` and/or `enabled-class` **are** defined:
81
+ * When **no** condition is met:
82
+ * If `enabled-class` is defined, it is removed from the wrapper
83
+ * If `disabled-class` is defined, it is added to the wrapper
84
+ * When **any** condition is met:
85
+ * If `enabled-class` is defined, it is added to the wrapper
86
+ * If `disabled-class` is defined, it is removed from the wrapper
87
+
88
+ ## Examples
89
+
90
+ ### Basic Usage
91
+
92
+ ```html
93
+ <form>
94
+ <label for="email">Email</label>
95
+ <input type="email" id="email" name="email">
96
+
97
+ <form-show-if conditions="email=*">
98
+ <label for="phone">Phone (shown if email provided)</label>
99
+ <input type="tel" id="phone" name="phone">
100
+ </form-show-if>
101
+
102
+ <button type="submit">Submit</button>
103
+ </form>
104
+ ```
105
+
106
+ ### Multiple Conditions (OR logic)
107
+
108
+ ```html
109
+ <form-show-if conditions="email=*||phone=*">
110
+ <label for="name">Name (shown if email OR phone provided)</label>
111
+ <input type="text" id="name" name="name">
112
+ </form-show-if>
113
+ ```
114
+
115
+ ### Specific Value Conditions
116
+
117
+ ```html
118
+ <form-show-if conditions="contact-method=email">
119
+ <label for="email">Email Address</label>
120
+ <input type="email" id="email" name="email">
121
+ </form-show-if>
122
+ ```
123
+
124
+ ### Checkbox Conditions
125
+
126
+ ```html
127
+ <form-show-if conditions="newsletter=yes">
128
+ <label for="email">Email (shown for newsletter)</label>
129
+ <input type="email" id="email" name="email">
130
+ </form-show-if>
131
+ ```
132
+
133
+ ### Using Custom Classes
134
+
135
+ ```html
136
+ <form-show-if conditions="email=*" disabled-class="visually-hidden" enabled-class="is-visible">
137
+ <label for="phone">Phone</label>
138
+ <input type="tel" id="phone" name="phone">
139
+ </form-show-if>
140
+ ```
141
+
142
+ ## Demo
143
+
144
+ [Live Demo](https://aarongustafson.github.io/form-show-if/demo.html) ([Source](./demo.html))
145
+
146
+ ## Browser Support
147
+
148
+ This web component works in all modern browsers that support:
149
+ - Custom Elements v1
150
+ - ES Modules (for module usage)
151
+
152
+ For older browsers, you may need polyfills for Custom Elements.
153
+
154
+ ## Development
155
+
156
+ ### Testing
157
+
158
+ ```bash
159
+ # Run tests
160
+ npm test
161
+
162
+ # Run tests once
163
+ npm run test:run
164
+
165
+ # Run tests with UI
166
+ npm run test:ui
167
+
168
+ # Run tests with coverage
169
+ npm run test:coverage
170
+ ```
171
+
172
+ ### Linting and Formatting
173
+
174
+ ```bash
175
+ # Lint code
176
+ npm run lint
177
+
178
+ # Format code
179
+ npm run format
180
+ ```
@@ -0,0 +1,62 @@
1
+ {
2
+ "schemaVersion": "2.1.0",
3
+ "readme": "README.md",
4
+ "modules": [
5
+ {
6
+ "kind": "javascript-module",
7
+ "path": "form-show-if.js",
8
+ "declarations": [
9
+ {
10
+ "kind": "class",
11
+ "customElement": true,
12
+ "name": "FormShowIfElement",
13
+ "tagName": "form-show-if",
14
+ "description": "Web component that enables you to make one HTML form field show (or not) based on the value(s) of another field.",
15
+ "members": [],
16
+ "attributes": [
17
+ {
18
+ "name": "conditions",
19
+ "description": "A double pipe (||) separated list of `name`/`value` pairs that, if true, would make this field show",
20
+ "type": {
21
+ "text": "string"
22
+ }
23
+ },
24
+ {
25
+ "name": "disabled-class",
26
+ "description": "An optional attribute declaring the `class` to use when the field is disabled. Used in lieu of the `hidden` attribute.",
27
+ "type": {
28
+ "text": "string"
29
+ }
30
+ },
31
+ {
32
+ "name": "enabled-class",
33
+ "description": "An optional attribute declaring the `class` to use when the field is enabled.",
34
+ "type": {
35
+ "text": "string"
36
+ }
37
+ }
38
+ ],
39
+ "superclass": {
40
+ "name": "HTMLElement"
41
+ }
42
+ }
43
+ ],
44
+ "exports": [
45
+ {
46
+ "kind": "js",
47
+ "name": "FormShowIfElement",
48
+ "declaration": {
49
+ "name": "FormShowIfElement"
50
+ }
51
+ },
52
+ {
53
+ "kind": "custom-element-definition",
54
+ "name": "form-show-if",
55
+ "declaration": {
56
+ "name": "FormShowIfElement"
57
+ }
58
+ }
59
+ ]
60
+ }
61
+ ]
62
+ }
package/define.js ADDED
@@ -0,0 +1,5 @@
1
+ import { FormShowIfElement } from './form-show-if.js';
2
+
3
+ if (!!customElements) {
4
+ customElements.define('form-show-if', FormShowIfElement);
5
+ }
@@ -0,0 +1,178 @@
1
+ export class FormShowIfElement extends HTMLElement {
2
+ connectedCallback() {
3
+ // Ensures Light DOM is available
4
+ setTimeout(() => {
5
+ this.__$wrapper = this;
6
+ this.__$field = this.querySelector(
7
+ 'input:not([type=submit],[type=reset],[type=image],[type=button]),select,textarea',
8
+ );
9
+ this.__$form = this.closest('form');
10
+ this.__$fields = [this.__$field];
11
+
12
+ this.__conditions = this.getAttribute('conditions').split('||');
13
+
14
+ this.__is_shown = null;
15
+ this.__disabledClass = this.getAttribute('disabled-class');
16
+ this.__enabledClass = this.getAttribute('enabled-class');
17
+
18
+ this.__init();
19
+ });
20
+ }
21
+
22
+ __addObservers() {
23
+ const reset = () => {
24
+ setTimeout(this.__checkIfShouldShow.bind(this), 100);
25
+ };
26
+ this.__$form.addEventListener('reset', reset.bind(this), false);
27
+ this.__$form.addEventListener(
28
+ 'change',
29
+ this.__checkIfShouldShow.bind(this),
30
+ false,
31
+ );
32
+ this.__$form.addEventListener(
33
+ 'input',
34
+ this.__checkIfShouldShow.bind(this),
35
+ false,
36
+ );
37
+ }
38
+
39
+ __determineWrapper() {
40
+ let $wrapper = this.__$field.parentElement;
41
+ while ($wrapper.querySelector('label') === null) {
42
+ if ($wrapper === this) {
43
+ break;
44
+ }
45
+ $wrapper = $wrapper.parentElement;
46
+ }
47
+ this.__$wrapper = $wrapper;
48
+ }
49
+
50
+ __gatherSiblingFields() {
51
+ const $fields = this.querySelectorAll(`[name="${this.__$field.name}"]`);
52
+ if ($fields.length) {
53
+ this.__$fields = [...this.__$fields, $fields];
54
+ }
55
+ }
56
+
57
+ // Wrapper `class` Management
58
+ __toggleEnabledClass() {
59
+ if (!this.__enabledClass) {
60
+ return;
61
+ }
62
+ if (this.__is_shown) {
63
+ this.__$wrapper.classList.add(this.__enabledClass);
64
+ } else {
65
+ this.__$wrapper.classList.remove(this.__enabledClass);
66
+ }
67
+ }
68
+ __toggleDisabledClass() {
69
+ if (!this.__disabledClass) {
70
+ return;
71
+ }
72
+ if (!this.__is_shown) {
73
+ this.__$wrapper.classList.add(this.__disabledClass);
74
+ } else {
75
+ this.__$wrapper.classList.remove(this.__disabledClass);
76
+ }
77
+ }
78
+ __toggleClasses() {
79
+ this.__toggleEnabledClass();
80
+ this.__toggleDisabledClass();
81
+ }
82
+
83
+ // Show / Hide Logic
84
+ __showField() {
85
+ this.__is_shown = true;
86
+ // Wrapper changes
87
+ if (!this.__disabledClass) {
88
+ this.__$wrapper.removeAttribute('hidden');
89
+ }
90
+ this.__toggleClasses();
91
+ // Disable field submission
92
+ this.__$fields.forEach(($field) => {
93
+ $field.disabled = false;
94
+ });
95
+ }
96
+ __hideField() {
97
+ this.__is_shown = false;
98
+ // Wrapper changes
99
+ if (!this.__disabledClass) {
100
+ this.__$wrapper.hidden = true;
101
+ }
102
+ this.__toggleClasses();
103
+ // Enable field submission
104
+ this.__$fields.forEach(($field) => {
105
+ $field.disabled = true;
106
+ });
107
+ }
108
+
109
+ __checkIfShouldShow() {
110
+ let should_show = false;
111
+ let test_conditions = this.__conditions;
112
+ test_conditions.some((condition) => {
113
+ const [name, value] = condition.split('=');
114
+
115
+ const $field = this.__$form.elements[name];
116
+ if (!$field) {
117
+ return;
118
+ }
119
+
120
+ const current_value = FormShowIfElement.__getCurrentValue($field);
121
+ if (FormShowIfElement.__valuesMatch(value, current_value)) {
122
+ should_show = true;
123
+ return true;
124
+ }
125
+ return false;
126
+ });
127
+
128
+ if (should_show && this.__is_shown !== true) {
129
+ this.__showField();
130
+ } else if (!should_show && this.__is_shown !== false) {
131
+ this.__hideField();
132
+ }
133
+ }
134
+
135
+ __init() {
136
+ this.__determineWrapper();
137
+ this.__gatherSiblingFields();
138
+ this.__addObservers();
139
+ this.__checkIfShouldShow();
140
+ }
141
+
142
+ static __getCurrentValue($field) {
143
+ // Checkboxes are special
144
+ if ($field.length && $field[0].type && $field[0].type == 'checkbox') {
145
+ let value = [];
146
+ let length = $field.length;
147
+ while (length--) {
148
+ let $current_field = $field[length];
149
+ if ($current_field.checked) {
150
+ value.push($current_field.value);
151
+ }
152
+ }
153
+ value.reverse();
154
+ return value;
155
+ }
156
+ return $field.value;
157
+ }
158
+
159
+ static __valuesMatch(condition_value, current_value) {
160
+ let match = false;
161
+
162
+ // precise match
163
+ if (condition_value == current_value) {
164
+ match = true;
165
+ } else if (condition_value == '*' && current_value != '') {
166
+ // Anything
167
+ match = true;
168
+ } else if (
169
+ current_value instanceof Array &&
170
+ current_value.includes(condition_value)
171
+ ) {
172
+ // Checkboxes
173
+ match = true;
174
+ }
175
+
176
+ return match;
177
+ }
178
+ }
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { FormShowIfElement } from './form-show-if.js';
2
+ import './define.js';
package/package.json ADDED
@@ -0,0 +1,80 @@
1
+ {
2
+ "name": "@aarongustafson/form-show-if",
3
+ "version": "2.0.0",
4
+ "description": "Web component that enables you to make one HTML form field show (or not) based on the value(s) of another field.",
5
+ "keywords": [
6
+ "html",
7
+ "custom element",
8
+ "web component",
9
+ "forms",
10
+ "form validation",
11
+ "conditional fields",
12
+ "show-hide",
13
+ "accessibility",
14
+ "a11y"
15
+ ],
16
+ "author": "Aaron Gustafson <aaron@easy-designs.net> (https://www.aaron-gustafson.com/)",
17
+ "license": "MIT",
18
+ "homepage": "https://github.com/aarongustafson/form-show-if#readme",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/aarongustafson/form-show-if.git"
22
+ },
23
+ "bugs": {
24
+ "url": "https://github.com/aarongustafson/form-show-if/issues"
25
+ },
26
+ "type": "module",
27
+ "main": "index.js",
28
+ "module": "form-show-if.js",
29
+ "customElements": "custom-elements.json",
30
+ "exports": {
31
+ ".": {
32
+ "import": "./index.js"
33
+ },
34
+ "./form-show-if.js": {
35
+ "import": "./form-show-if.js"
36
+ },
37
+ "./define.js": {
38
+ "import": "./define.js"
39
+ },
40
+ "./custom-elements.json": "./custom-elements.json"
41
+ },
42
+ "files": [
43
+ "form-show-if.js",
44
+ "define.js",
45
+ "index.js",
46
+ "custom-elements.json",
47
+ "README.md",
48
+ "LICENSE"
49
+ ],
50
+ "engines": {
51
+ "node": ">=14.0.0"
52
+ },
53
+ "scripts": {
54
+ "test": "vitest",
55
+ "test:ui": "vitest --ui",
56
+ "test:run": "vitest run",
57
+ "test:coverage": "vitest run --coverage",
58
+ "lint": "npm run lint:eslint && npm run lint:prettier",
59
+ "format": "npm run format:eslint && npm run format:prettier",
60
+ "lint:eslint": "eslint .",
61
+ "format:eslint": "eslint . --fix",
62
+ "lint:prettier": "prettier \"**/*.js\" --check --ignore-path .gitignore",
63
+ "format:prettier": "prettier \"**/*.js\" --write --ignore-path .gitignore"
64
+ },
65
+ "devDependencies": {
66
+ "@open-wc/eslint-config": "^13.0.0",
67
+ "@testing-library/dom": "^10.4.1",
68
+ "@testing-library/user-event": "^14.6.1",
69
+ "@vitest/coverage-v8": "^4.0.10",
70
+ "@vitest/ui": "^4.0.10",
71
+ "eslint": "^9.39.1",
72
+ "eslint-config-prettier": "^10.1.8",
73
+ "happy-dom": "^20.0.10",
74
+ "prettier": "^3.6.2",
75
+ "vitest": "^4.0.10"
76
+ },
77
+ "publishConfig": {
78
+ "access": "public"
79
+ }
80
+ }