Skip to content

Instantly share code, notes, and snippets.

@claviska
Last active February 15, 2022 16:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save claviska/8182d81a0c9c8f9d7554655e14ba56e5 to your computer and use it in GitHub Desktop.
Save claviska/8182d81a0c9c8f9d7554655e14ba56e5 to your computer and use it in GitHub Desktop.
A Reactive Controller for Custom Element Form Controls
//
// This is a Reactive Controller (https://lit.dev/docs/composition/controllers/) that allows custom elements to submit
// with standard <form> elements.
//
// The formdata event didn't land in Safari until 15.1, which is still somewhat recent. You can use this lightweight
// polyfill to make it work: https://gist.github.com/WickyNilliams/eb6a44075356ee504dd9491c5a3ab0be
//
// If your custom element shares the same API as HTMLInputElement for name/value/disabled/reportValidity, this is all
// you need to do:
//
// @customElement('my-input')
// export default class MyInput extends LitElement {
// private formSubmitController = new FormSubmitController(this);
// ...
// }
//
// Note that checkboxes and radios need special treatment so they only submit when checked. Returning undefined in the
// mapping will omit the form control from the resulting FormData object.
//
// private formSubmitController = new FormSubmitController(this, {
// value: checkbox => checkbox.checked ? checkbox.value : undefined
// });
//
// If your custom element has a unique API, you can map each property like this.
//
// private formSubmitController = new FormSubmitController(this, {
// name: input => input.name,
// value: input => input.value,
// disabled: input => input.disabled,
// reportValidity: input => input.reportValidity()
// });
//
// Note that reportValidity should point to a native <input> element's reportValidity() method if you wish to support
// the constraint validation API.
//
// MIT LICENSE
//
// Copyright (c) 2020 A Beautiful Site, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import { ReactiveController, ReactiveControllerHost } from 'lit';
export interface FormSubmitControllerOptions {
/** A function that returns the form containing the form control. */
form: (input: unknown) => HTMLFormElement;
/** A function that returns the form control's name, which will be submitted with the form data. */
name: (input: unknown) => string;
/** A function that returns the form control's current value. */
value: (input: unknown) => any;
/** A function that returns the form control's current disabled state. If disabled, the value won't be submitted. */
disabled: (input: unknown) => boolean;
/**
* A function that maps to the form control's reportValidity() function. When the control is invalid, this will
* prevent submission and trigger the browser's constraint violation warning.
*/
reportValidity: (input: unknown) => boolean;
}
export class FormSubmitController implements ReactiveController {
host?: ReactiveControllerHost & Element;
form?: HTMLFormElement;
options?: FormSubmitControllerOptions;
constructor(host: ReactiveControllerHost & Element, options?: FormSubmitControllerOptions) {
(this.host = host).addController(this);
this.options = Object.assign(
{
form: (input: HTMLInputElement) => input.closest('form'),
name: (input: HTMLInputElement) => input.name,
value: (input: HTMLInputElement) => input.value,
disabled: (input: HTMLInputElement) => input.disabled,
reportValidity: (input: HTMLInputElement) => {
return typeof input.reportValidity === 'function' ? input.reportValidity() : true;
}
},
options
);
this.handleFormData = this.handleFormData.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
}
hostConnected() {
this.form = this.options?.form(this.host);
if (this.form) {
this.form.addEventListener('formdata', this.handleFormData);
this.form.addEventListener('submit', this.handleFormSubmit);
}
}
hostDisconnected() {
if (this.form) {
this.form.removeEventListener('formdata', this.handleFormData);
this.form.removeEventListener('submit', this.handleFormSubmit);
this.form = undefined;
}
}
handleFormData(event: FormDataEvent) {
const disabled = this.options?.disabled(this.host);
const name = this.options?.name(this.host);
const value = this.options?.value(this.host);
if (!disabled && name && value !== undefined) {
if (Array.isArray(value)) {
value.map(val => event.formData.append(name, val));
} else {
event.formData.append(name, value);
}
}
}
handleFormSubmit(event: Event) {
const form = this.form;
const disabled = this.options?.disabled(this.host);
const reportValidity = this.options?.reportValidity;
if (form && !form.noValidate && !disabled && reportValidity && !reportValidity(this.host)) {
event.preventDefault();
event.stopImmediatePropagation();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment