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(Input): enable support for form-associated #1211

Merged
merged 3 commits into from
Aug 14, 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
Original file line number Diff line number Diff line change
Expand Up @@ -262,3 +262,89 @@ export const NoHelperText: Story = {
suffix: true,
},
};

export const WithForm: Story = {
render: () => {
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>
<h4 class="m-be-m">Shipping Information</h4>
<form class="flex flex-col gap-y-m" @submit=${handleFormSubmit}>
<div class="grid grid-cols-1 gap-y-m sm:grid-cols-2 sm:gap-x-m">
<bq-input name="firstName" value="Brad Bernie" autocomplete="given-name" required>
<label class="flex flex-grow items-center" slot="label">First Name</label>
</bq-input>
<bq-input name="lastName" value="Beckett" autocomplete="family-name" required>
<label class="flex flex-grow items-center" slot="label">Last Name</label>
</bq-input>
</div>
<bq-input name="company" value="Endava" autocomplete="organization" required>
<label class="flex flex-grow items-center" slot="label">Company</label>
</bq-input>
<bq-input name="address" value="413 South Ohio Ave" autocomplete="shipping street-address" required>
<label class="flex flex-grow items-center" slot="label">Address</label>
</bq-input>
<div class="grid grid-cols-1 gap-y-m sm:grid-cols-2 sm:gap-x-m" autocomplete="address-level2">
<bq-input name="city" value="Oklahoma" required>
<label class="flex flex-grow items-center" slot="label">City</label>
</bq-input>
<bq-select name="country" value="us" autocomplete="country-name">
<label class="flex flex-grow items-center" slot="label">Country</label>
<bq-option value="au">Australia</bq-option>
<bq-option value="ca">Canada</bq-option>
<bq-option value="mx">Mexico</bq-option>
<bq-option value="pt">Portugal</bq-option>
<bq-option value="ro">Romania</bq-option>
<bq-option value="us">United States</bq-option>
</bq-select>
</div>
<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>
`;
},
};
44 changes: 34 additions & 10 deletions packages/beeq/src/components/input/bq-input.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Component, Element, Event, EventEmitter, h, Prop, State, Watch } from '@stencil/core';
import { AttachInternals, Component, Element, Event, EventEmitter, h, Prop, State, Watch } from '@stencil/core';

import { TInputType, TInputValidation, TInputValue } from './bq-input.types';
import { debounce, hasSlotContent, isDefined, isHTMLElement, TDebounce } from '../../shared/utils';
import { debounce, hasSlotContent, isDefined, isHTMLElement, isNil, TDebounce } from '../../shared/utils';

/**
* @part base - The component's base wrapper.
Expand All @@ -17,6 +17,7 @@ import { debounce, hasSlotContent, isDefined, isHTMLElement, TDebounce } from '.
@Component({
tag: 'bq-input',
styleUrl: './scss/bq-input.scss',
formAssociated: true,
shadow: {
delegatesFocus: true,
},
Expand All @@ -38,6 +39,7 @@ export class BqInput {
// ===================================

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

// State() variables
// Inlined decorator, alphabetical order
Expand Down Expand Up @@ -174,10 +176,12 @@ export class BqInput {
handleValueChange() {
if (Array.isArray(this.value)) {
this.hasValue = this.value.some((val) => val.length > 0);
this.internals.setFormValue(this.value.join(','));
return;
}

this.hasValue = isDefined(this.value);
this.internals.setFormValue(`${this.value}`);
}

// Events section
Expand Down Expand Up @@ -209,10 +213,16 @@ export class BqInput {
// Ordered by their natural call order
// =====================================

componentDidLoad() {
componentWillLoad() {
this.handleValueChange();
}

formResetCallback() {
if (isNil(this.value)) return;

this.handleClear();
}

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

Expand Down Expand Up @@ -247,6 +257,7 @@ export class BqInput {

if (!isHTMLElement(ev.target, 'input')) return;
this.value = this.type === 'number' ? Number(ev.target.value) : ev.target.value;
this.internals.setFormValue(`${this.value}`);

this.debounceBqInput = debounce(() => {
this.bqInput.emit({ value: this.value, el: this.el });
Expand All @@ -259,22 +270,35 @@ export class BqInput {

if (!isHTMLElement(ev.target, 'input')) return;
this.value = this.type === 'number' ? Number(ev.target.value) : ev.target.value;
this.internals.setFormValue(`${this.value}`);

this.bqChange.emit({ value: this.value, el: this.el });
};

private handleClearClick = (ev: CustomEvent) => {
private handleClear = () => {
if (this.disabled) return;

this.inputElem.value = '';
this.value = this.inputElem.value;
const { inputElem, internals } = this;

this.bqClear.emit(this.el);
this.bqInput.emit({ value: this.value, el: this.el });
this.bqChange.emit({ value: this.value, el: this.el });
this.inputElem.focus();
// Clear input element value
inputElem.value = '';
this.value = inputElem.value;

// Update associated form control value
internals.setFormValue(undefined);
};

private handleClearClick = (ev: CustomEvent) => {
ev.stopPropagation();
this.handleClear();

const { bqClear, bqChange, bqInput, el, inputElem } = this;
// Emit events
bqClear.emit(el);
bqInput.emit({ value: this.value, el });
bqChange.emit({ value: this.value, el });
// Refocus input element
inputElem.focus();
};

private handleLabelSlotChange = () => {
Expand Down