Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Switch): enable support for form-associated #1368

Merged
merged 4 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/beeq/src/components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2351,6 +2351,7 @@ export namespace Components {
* @attr {boolean} background-on-hover - If `true`, a background will be displayed on hover
* @attr {boolean} checked - It indicates whether if the switch is `ON` by default (when the page loads)
* @attr {boolean} disabled - If `true`, the switch control will be disabled and no interaction will be allowed
* @attr {string} form-validation-message - The native form validation message
* @attr {boolean} full-width - If `true`, the component will take the full width space available on the parent container
* @attr {"default" | "icon"} inner-label - It indicates how to to display the on/off marks inside the control, with icons or none (default)
* @attr {"start" | "end" | "center" | "space-between" | "space-around" | "space-evenly"} justify-content - It defines how to distribute the space between and around the control and the label text
Expand Down Expand Up @@ -2379,6 +2380,10 @@ export namespace Components {
* If true, the switch control will be disabled and no interaction will be allowed
*/
"disabled"?: boolean;
/**
* The native form validation message
*/
"formValidationMessage"?: string;
/**
* If true, the component will take the full width space available on the parent container
*/
Expand Down Expand Up @@ -4710,6 +4715,7 @@ declare global {
* @attr {boolean} background-on-hover - If `true`, a background will be displayed on hover
* @attr {boolean} checked - It indicates whether if the switch is `ON` by default (when the page loads)
* @attr {boolean} disabled - If `true`, the switch control will be disabled and no interaction will be allowed
* @attr {string} form-validation-message - The native form validation message
* @attr {boolean} full-width - If `true`, the component will take the full width space available on the parent container
* @attr {"default" | "icon"} inner-label - It indicates how to to display the on/off marks inside the control, with icons or none (default)
* @attr {"start" | "end" | "center" | "space-between" | "space-around" | "space-evenly"} justify-content - It defines how to distribute the space between and around the control and the label text
Expand Down Expand Up @@ -7586,6 +7592,7 @@ declare namespace LocalJSX {
* @attr {boolean} background-on-hover - If `true`, a background will be displayed on hover
* @attr {boolean} checked - It indicates whether if the switch is `ON` by default (when the page loads)
* @attr {boolean} disabled - If `true`, the switch control will be disabled and no interaction will be allowed
* @attr {string} form-validation-message - The native form validation message
* @attr {boolean} full-width - If `true`, the component will take the full width space available on the parent container
* @attr {"default" | "icon"} inner-label - It indicates how to to display the on/off marks inside the control, with icons or none (default)
* @attr {"start" | "end" | "center" | "space-between" | "space-around" | "space-evenly"} justify-content - It defines how to distribute the space between and around the control and the label text
Expand Down Expand Up @@ -7614,6 +7621,10 @@ declare namespace LocalJSX {
* If true, the switch control will be disabled and no interaction will be allowed
*/
"disabled"?: boolean;
/**
* The native form validation message
*/
"formValidationMessage"?: string;
/**
* If true, the component will take the full width space available on the parent container
*/
Expand Down Expand Up @@ -9454,6 +9465,7 @@ declare module "@stencil/core" {
* @attr {boolean} background-on-hover - If `true`, a background will be displayed on hover
* @attr {boolean} checked - It indicates whether if the switch is `ON` by default (when the page loads)
* @attr {boolean} disabled - If `true`, the switch control will be disabled and no interaction will be allowed
* @attr {string} form-validation-message - The native form validation message
* @attr {boolean} full-width - If `true`, the component will take the full width space available on the parent container
* @attr {"default" | "icon"} inner-label - It indicates how to to display the on/off marks inside the control, with icons or none (default)
* @attr {"start" | "end" | "center" | "space-between" | "space-around" | "space-evenly"} justify-content - It defines how to distribute the space between and around the control and the label text
Expand Down
13 changes: 5 additions & 8 deletions packages/beeq/src/components/checkbox/bq-checkbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -160,10 +160,12 @@ export class BqCheckbox {
}

formResetCallback() {
this.clearSelection();
// Reset the form value and validity state
this.internals.setFormValue(undefined);
this.internals.setValidity({});
this.checked = false;
this.indeterminate = false;
this.inputElem.removeAttribute('checked');
this.internals?.setFormValue(undefined);
this.updateFormValidity();
}

// Listeners
Expand Down Expand Up @@ -233,11 +235,6 @@ export class BqCheckbox {
internals?.setValidity({ valueMissing: true }, formValidationMessage, inputElem);
};

private clearSelection = () => {
this.checked = false;
this.indeterminate = false;
};

private handleChange = () => {
this.checked = !this.checked;
this.indeterminate = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@

.bq-checkbox__input {
// Checkbox square icon has `FOCUS`
&:focus,
&:focus-visible {
~ .bq-checkbox__checkbox {
@apply focus border-brand;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const meta: Meta = {
'background-on-hover': { control: 'boolean' },
checked: { control: 'boolean' },
disabled: { control: 'boolean' },
'form-validation-message': { control: 'text' },
'full-width': { control: 'boolean' },
'inner-label': { control: 'inline-radio', options: [...SWITCH_INNER_LABEL] },
'justify-content': { control: 'select', options: [...SWITCH_JUSTIFY_CONTENT] },
Expand All @@ -35,6 +36,7 @@ const meta: Meta = {
'background-on-hover': false,
checked: false,
disabled: false,
'form-validation-message': undefined,
'full-width': false,
'inner-label': 'default',
'justify-content': 'start',
Expand All @@ -55,6 +57,7 @@ const Template = (args: Args) => html`
?background-on-hover=${args['background-on-hover']}
?checked=${args.checked}
?disabled=${args.disabled}
form-validation-message=${ifDefined(args['form-validation-message'])}
?full-width=${args['full-width']}
inner-label=${ifDefined(args['inner-label'])}
justify-content=${ifDefined(args['justify-content'])}
Expand Down Expand Up @@ -124,3 +127,76 @@ export const FullWidth: Story = {
'reverse-order': true,
},
};

export const WithForm: Story = {
render: (args: Args) => {
const handleFormSubmit = (ev: Event) => {
ev.preventDefault();
const form = ev.target as HTMLFormElement;
const formData = new FormData(form);
const formValues = Object.fromEntries(formData.entries());

const codeElement = document.getElementById('form-data');
if (!codeElement) return;

codeElement.textContent = JSON.stringify(formValues, null, 2);
};

return html`
<link rel="stylesheet" href="https://unpkg.com/@highlightjs/[email protected]/styles/night-owl.min.css" />
<div class="grid auto-cols-auto grid-cols-1 gap-y-l sm:grid-cols-2 sm:gap-x-l">
<bq-card style="--bq-card--background: transparent">
<h4 class="m-be-m">Account settings</h4>
<form class="flex flex-col gap-y-m" @submit=${handleFormSubmit}>
${Template({
...args,
text: 'Show app list in the menu',
name: 'showAppList',
required: true,
'form-validation-message': 'Please enable showing the app list in the menu',
})}
${Template({ ...args, text: 'Show recently added apps', name: 'showRecentlyApps', checked: true })}
${Template({ ...args, text: 'Show most used apps', name: 'showUsedApps' })}
${Template({ ...args, text: 'Show app notifications', name: 'showAppNotifications', checked: true })}
<div class="flex justify-end gap-x-s">
<bq-button appearance="secondary" type="reset">Cancel</bq-button>
<bq-button type="submit">Save</bq-button>
</div>
</form>
</bq-card>
<bq-card class="[&::part(wrapper)]:h-full">
<h4 class="m-be-m">Form Data</h4>
<div class="language-javascript overflow-x-scroll whitespace-pre rounded-s">
// Handle form submit<br />
const form = ev.target as HTMLFormElement;<br />
const formData = new FormData(form);<br />
const formValues = Object.fromEntries(formData.entries());
</div>
<pre>
<code id="form-data" class="rounded-s">
{ // submit the form to see the data here }
</code>
</pre>
</bq-card>
</div>

<script type="module">
import hljs from 'https://unpkg.com/@highlightjs/[email protected]/es/highlight.min.js';
import javascript from 'https://unpkg.com/@highlightjs/[email protected]/es/languages/javascript.min.js';

hljs.registerLanguage('javascript', javascript);
hljs.highlightAll();

document.querySelectorAll('div.language-javascript').forEach((block) => {
hljs.highlightElement(block);
});
</script>
`;
},
args: {
'background-on-hover': true,
'full-width': true,
'justify-content': 'space-between',
'reverse-order': true,
},
};
68 changes: 66 additions & 2 deletions packages/beeq/src/components/switch/bq-switch.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
import { Component, Element, Event, EventEmitter, h, Host, Method, Prop, State } from '@stencil/core';
import {
AttachInternals,
Component,
Element,
Event,
EventEmitter,
h,
Host,
Method,
Prop,
State,
Watch,
} from '@stencil/core';

import { TSwitchInnerLabel, TSwitchJustifyContent } from './bq-switch.types';
import { getTextContent, isNil } from '../../shared/utils';
Expand All @@ -22,6 +34,7 @@ import { getTextContent, isNil } from '../../shared/utils';
* @attr {boolean} background-on-hover - If `true`, a background will be displayed on hover
* @attr {boolean} checked - It indicates whether if the switch is `ON` by default (when the page loads)
* @attr {boolean} disabled - If `true`, the switch control will be disabled and no interaction will be allowed
* @attr {string} form-validation-message - The native form validation message
* @attr {boolean} full-width - If `true`, the component will take the full width space available on the parent container
* @attr {"default" | "icon"} inner-label - It indicates how to to display the on/off marks inside the control, with icons or none (default)
* @attr {"start" | "end" | "center" | "space-between" | "space-around" | "space-evenly"} justify-content - It defines how to distribute the space between and around the control and the label text
Expand Down Expand Up @@ -51,6 +64,7 @@ import { getTextContent, isNil } from '../../shared/utils';
@Component({
tag: 'bq-switch',
styleUrl: './scss/bq-switch.scss',
formAssociated: true,
shadow: {
delegatesFocus: true,
},
Expand All @@ -66,6 +80,7 @@ export class BqSwitch {
// Reference to host HTML element
// ===================================

@AttachInternals() internals!: ElementInternals;
@Element() el!: HTMLBqSwitchElement;

// State() variables
Expand All @@ -86,6 +101,9 @@ export class BqSwitch {
/** If true, the switch control will be disabled and no interaction will be allowed */
@Prop({ reflect: true }) disabled?: boolean = false;

/** The native form validation message */
@Prop({ mutable: true }) formValidationMessage?: string;

/** If true, the component will take the full width space available on the parent container */
@Prop({ reflect: true }) fullWidth?: boolean = false;

Expand Down Expand Up @@ -113,6 +131,11 @@ export class BqSwitch {
// Prop lifecycle events
// =======================

@Watch('required')
handleRequiredChange() {
this.updateFormValidity();
}

// Events section
// Requires JSDocs for public API documentation
// ==============================================
Expand Down Expand Up @@ -150,6 +173,20 @@ export class BqSwitch {
}
}

formAssociatedCallback() {
console.log('formAssociatedCallback...');
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
console.log('formAssociatedCallback...');

this.setFormValue(this.checked);
this.updateFormValidity();
}

formResetCallback() {
// Reset the form value and validity state
this.checked = false;
this.inputElem.removeAttribute('checked');
this.internals?.setFormValue(undefined);
this.updateFormValidity();
}

// Listeners
// ==============

Expand Down Expand Up @@ -195,6 +232,8 @@ export class BqSwitch {
private handleChange = () => {
this.checked = !this.checked;
this.inputElem.setAttribute('checked', `${this.checked}`);
this.setFormValue(this.checked);
this.updateFormValidity();
};

private handleOnFocus = () => {
Expand All @@ -212,6 +251,31 @@ export class BqSwitch {
this.hasLabel = !!getTextContent(slot, { recurse: true }).length;
};

private setFormValue = (checked: boolean) => {
const value = checked ? 'on' : undefined;
// Set form value based on the checked state
// Here we also pass the state of the component (2nd argument) as the state of the form control
// Details: https://developer.mozilla.org/en-US/docs/Web/API/ElementInternals/setFormValue
this.internals?.setFormValue(value, `${this.checked}`);
};

private updateFormValidity = () => {
const { formValidationMessage, internals, required, checked, inputElem } = this;
// Clear the validity state
internals?.states.clear();

if (!(required && !checked)) {
// If the switch component is not required or is checked, set the validity state to valid
internals?.states.add('valid');
internals?.setValidity({});
return;
}

// Set validity state based on the required property and checked state
internals?.states.add('invalid');
internals?.setValidity({ valueMissing: true }, formValidationMessage, inputElem);
};

// render() function
// Always the last one in the class.
// ===================================
Expand All @@ -233,7 +297,7 @@ export class BqSwitch {
<label class={{ 'bq-switch group': true, ...labelCssClasses }} part="base">
{/* Hidden native HTML input */}
<input
class="bq-switch--input peer sr-only peer-checked:invisible"
class="bq-switch--input peer sr-only !bs-[--bq-switch--dot-size] !is-[--bq-switch--width] peer-checked:invisible"
type="checkbox"
checked={this.checked}
disabled={this.disabled}
Expand Down
Loading