mirror of
https://github.com/shoelace-style/webawesome.git
synced 2026-01-12 12:09:26 +00:00
support for <form> elements; remove <sl-form>
This commit is contained in:
@@ -4,6 +4,7 @@ import { html, literal } from 'lit/static-html.js';
|
||||
import { classMap } from 'lit/directives/class-map.js';
|
||||
import { ifDefined } from 'lit/directives/if-defined.js';
|
||||
import { emit } from '../../internal/event';
|
||||
import { FormSubmitController } from '../../internal/form-control';
|
||||
import { HasSlotController } from '../../internal/slot';
|
||||
import styles from './button.styles';
|
||||
|
||||
@@ -34,6 +35,7 @@ export default class SlButton extends LitElement {
|
||||
|
||||
@query('.button') button: HTMLButtonElement | HTMLLinkElement;
|
||||
|
||||
private formSubmitController = new FormSubmitController(this);
|
||||
private hasSlotController = new HasSlotController(this, '[default]', 'prefix', 'suffix');
|
||||
|
||||
@state() private hasFocus = false;
|
||||
@@ -63,8 +65,11 @@ export default class SlButton extends LitElement {
|
||||
/** Draws a circle button. */
|
||||
@property({ type: Boolean, reflect: true }) circle = false;
|
||||
|
||||
/** Indicates if activating the button should submit the form. Ignored when `href` is set. */
|
||||
@property({ type: Boolean, reflect: true }) submit = false;
|
||||
/**
|
||||
* The type of button. When the type is `submit`, the button will submit the surrounding form. Note that the default
|
||||
* value is `button` instead of `submit`, which is opposite of how native `<button>` elements behave.
|
||||
*/
|
||||
@property() type: 'button' | 'submit' = 'button';
|
||||
|
||||
/** An optional name for the button. Ignored when `href` is set. */
|
||||
@property() name: string;
|
||||
@@ -110,6 +115,11 @@ export default class SlButton extends LitElement {
|
||||
if (this.disabled || this.loading) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.type === 'submit') {
|
||||
this.formSubmitController.submit();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,7 +155,7 @@ export default class SlButton extends LitElement {
|
||||
'button--has-suffix': this.hasSlotController.test('suffix')
|
||||
})}
|
||||
?disabled=${ifDefined(isLink ? undefined : this.disabled)}
|
||||
type=${ifDefined(isLink ? undefined : this.submit ? 'submit' : 'button')}
|
||||
type=${this.type}
|
||||
name=${ifDefined(isLink ? undefined : this.name)}
|
||||
value=${ifDefined(isLink ? undefined : this.value)}
|
||||
href=${ifDefined(this.href)}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ifDefined } from 'lit/directives/if-defined.js';
|
||||
import { live } from 'lit/directives/live.js';
|
||||
import { emit } from '../../internal/event';
|
||||
import { watch } from '../../internal/watch';
|
||||
import { FormSubmitController } from '../../internal/form-control';
|
||||
import styles from './checkbox.styles';
|
||||
|
||||
let id = 0;
|
||||
@@ -31,6 +32,10 @@ export default class SlCheckbox extends LitElement {
|
||||
|
||||
@query('input[type="checkbox"]') input: HTMLInputElement;
|
||||
|
||||
// @ts-ignore
|
||||
private formSubmitController = new FormSubmitController(this, {
|
||||
value: (control: SlCheckbox) => (control.checked ? control.value : undefined)
|
||||
});
|
||||
private inputId = `checkbox-${++id}`;
|
||||
private labelId = `checkbox-label-${id}`;
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { styleMap } from 'lit/directives/style-map.js';
|
||||
import { emit } from '../../internal/event';
|
||||
import { watch } from '../../internal/watch';
|
||||
import { clamp } from '../../internal/math';
|
||||
import { FormSubmitController } from '../../internal/form-control';
|
||||
import { LocalizeController } from '../../utilities/localize';
|
||||
import type SlDropdown from '../dropdown/dropdown';
|
||||
import type SlInput from '../input/input';
|
||||
@@ -57,14 +58,16 @@ const hasEyeDropper = 'EyeDropper' in window;
|
||||
@customElement('sl-color-picker')
|
||||
export default class SlColorPicker extends LitElement {
|
||||
static styles = styles;
|
||||
private localize = new LocalizeController(this);
|
||||
|
||||
@query('[part="input"]') input: SlInput;
|
||||
@query('[part="preview"]') previewButton: HTMLButtonElement;
|
||||
@query('.color-dropdown') dropdown: SlDropdown;
|
||||
|
||||
// @ts-ignore
|
||||
private formSubmitController = new FormSubmitController(this);
|
||||
private isSafeValue = false;
|
||||
private lastValueEmitted: string;
|
||||
private localize = new LocalizeController(this);
|
||||
|
||||
@state() private inputValue = '';
|
||||
@state() private hue = 0;
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import { css } from 'lit';
|
||||
import componentStyles from '../../styles/component.styles';
|
||||
|
||||
export default css`
|
||||
${componentStyles}
|
||||
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
`;
|
||||
@@ -1,283 +0,0 @@
|
||||
import { LitElement, html } from 'lit';
|
||||
import { customElement, property, query } from 'lit/decorators.js';
|
||||
import { emit } from '../../internal/event';
|
||||
import type SlButton from '../button/button';
|
||||
import type SlCheckbox from '../checkbox/checkbox';
|
||||
import type SlColorPicker from '../color-picker/color-picker';
|
||||
import type SlInput from '../input/input';
|
||||
import type SlRadio from '../radio/radio';
|
||||
import type SlRange from '../range/range';
|
||||
import type SlSelect from '../select/select';
|
||||
import type SlSwitch from '../switch/switch';
|
||||
import type SlTextarea from '../textarea/textarea';
|
||||
import styles from './form.styles';
|
||||
|
||||
interface FormControl {
|
||||
tag: string;
|
||||
serialize: (el: HTMLElement, formData: FormData) => void;
|
||||
click?: (event: MouseEvent) => any;
|
||||
keyDown?: (event: KeyboardEvent) => any;
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 2.0
|
||||
* @status stable
|
||||
*
|
||||
* @slot - The form's content.
|
||||
*
|
||||
* @event {{ formData: FormData, formControls: [] }} sl-submit - Emitted when the form is submitted. This event will not
|
||||
* be emitted if any form control inside of it is in an invalid state, unless the form has the `novalidate` attribute.
|
||||
* Note that there is never a need to prevent this event, since it doesn't send a GET or POST request like native
|
||||
* forms. To "prevent" submission, use a conditional around the XHR request you use to submit the form's data with.
|
||||
*
|
||||
* @csspart base - The component's base wrapper.
|
||||
*/
|
||||
@customElement('sl-form')
|
||||
export default class SlForm extends LitElement {
|
||||
static styles = styles;
|
||||
|
||||
@query('.form') form: HTMLElement;
|
||||
|
||||
private formControls: FormControl[];
|
||||
|
||||
/** Prevent the form from validating inputs before submitting. */
|
||||
@property({ type: Boolean, reflect: true }) novalidate = false;
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
|
||||
this.formControls = [
|
||||
{
|
||||
tag: 'button',
|
||||
serialize: (el: HTMLButtonElement, formData) =>
|
||||
el.name && !el.disabled ? formData.append(el.name, el.value) : null,
|
||||
click: event => {
|
||||
const target = event.target as HTMLButtonElement;
|
||||
if (target.type === 'submit') {
|
||||
this.submit();
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
tag: 'input',
|
||||
serialize: (el: HTMLInputElement, formData) => {
|
||||
if (!el.name || el.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ((el.type === 'checkbox' || el.type === 'radio') && !el.checked) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (el.type === 'file') {
|
||||
[...(el.files as FileList)].map(file => formData.append(el.name, file));
|
||||
return;
|
||||
}
|
||||
|
||||
formData.append(el.name, el.value);
|
||||
},
|
||||
click: event => {
|
||||
const target = event.target as HTMLInputElement;
|
||||
if (target.type === 'submit') {
|
||||
this.submit();
|
||||
}
|
||||
},
|
||||
keyDown: event => {
|
||||
const target = event.target as HTMLInputElement;
|
||||
if (
|
||||
event.key === 'Enter' &&
|
||||
!event.defaultPrevented &&
|
||||
!['checkbox', 'file', 'radio'].includes(target.type)
|
||||
) {
|
||||
this.submit();
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
tag: 'select',
|
||||
serialize: (el: HTMLSelectElement, formData) => {
|
||||
if (el.name && !el.disabled) {
|
||||
if (el.multiple) {
|
||||
const selectedOptions = [...el.querySelectorAll('option:checked')];
|
||||
if (selectedOptions.length) {
|
||||
selectedOptions.map((option: HTMLOptionElement) => formData.append(el.name, option.value));
|
||||
} else {
|
||||
formData.append(el.name, '');
|
||||
}
|
||||
} else {
|
||||
formData.append(el.name, el.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
tag: 'sl-button',
|
||||
serialize: (el: SlButton, formData) => (el.name && !el.disabled ? formData.append(el.name, el.value) : null),
|
||||
click: event => {
|
||||
const target = event.target as SlButton;
|
||||
if (target.submit) {
|
||||
this.submit();
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
tag: 'sl-checkbox',
|
||||
serialize: (el: SlCheckbox, formData) =>
|
||||
el.name && el.checked && !el.disabled ? formData.append(el.name, el.value) : null
|
||||
},
|
||||
{
|
||||
tag: 'sl-color-picker',
|
||||
serialize: (el: SlColorPicker, formData) =>
|
||||
el.name && !el.disabled ? formData.append(el.name, el.value) : null
|
||||
},
|
||||
{
|
||||
tag: 'sl-input',
|
||||
serialize: (el: SlInput, formData) => (el.name && !el.disabled ? formData.append(el.name, el.value) : null),
|
||||
keyDown: event => {
|
||||
if (event.key === 'Enter' && !event.defaultPrevented) {
|
||||
this.submit();
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
tag: 'sl-radio',
|
||||
serialize: (el: SlRadio, formData) =>
|
||||
el.name && el.checked && !el.disabled ? formData.append(el.name, el.value) : null
|
||||
},
|
||||
{
|
||||
tag: 'sl-range',
|
||||
serialize: (el: SlRange, formData) => {
|
||||
if (el.name && !el.disabled) {
|
||||
formData.append(el.name, el.value + '');
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
tag: 'sl-select',
|
||||
serialize: (el: SlSelect, formData) => {
|
||||
if (el.name && !el.disabled) {
|
||||
if (el.multiple) {
|
||||
const selectedOptions = [...el.value];
|
||||
if (selectedOptions.length) {
|
||||
selectedOptions.map(value => formData.append(el.name, value));
|
||||
} else {
|
||||
formData.append(el.name, '');
|
||||
}
|
||||
} else {
|
||||
formData.append(el.name, el.value + '');
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
tag: 'sl-switch',
|
||||
serialize: (el: SlSwitch, formData) =>
|
||||
el.name && el.checked && !el.disabled ? formData.append(el.name, el.value) : null
|
||||
},
|
||||
{
|
||||
tag: 'sl-textarea',
|
||||
serialize: (el: SlTextarea, formData) => (el.name && !el.disabled ? formData.append(el.name, el.value) : null)
|
||||
},
|
||||
{
|
||||
tag: 'textarea',
|
||||
serialize: (el: HTMLTextAreaElement, formData) =>
|
||||
el.name && !el.disabled ? formData.append(el.name, el.value) : null
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
/** Serializes all form controls elements and returns a `FormData` object. */
|
||||
getFormData() {
|
||||
const formData = new FormData();
|
||||
const formControls = this.getFormControls();
|
||||
|
||||
formControls.map(el => this.serializeElement(el, formData));
|
||||
|
||||
return formData;
|
||||
}
|
||||
|
||||
/** Gets all form control elements (native and custom). */
|
||||
getFormControls() {
|
||||
const slot = this.form.querySelector('slot')!;
|
||||
const tags = this.formControls.map(control => control.tag);
|
||||
return slot
|
||||
.assignedElements({ flatten: true })
|
||||
.reduce(
|
||||
(all: HTMLElement[], el: HTMLElement) => all.concat(el, [...el.querySelectorAll('*')] as HTMLElement[]),
|
||||
[]
|
||||
)
|
||||
.filter((el: HTMLElement) => tags.includes(el.tagName.toLowerCase())) as HTMLElement[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits the form. If all controls are valid, the `sl-submit` event will be emitted and the promise will resolve
|
||||
* with `true`. If any form control is invalid, the promise will resolve with `false` and no event will be emitted.
|
||||
*/
|
||||
submit() {
|
||||
const formData = this.getFormData();
|
||||
const formControls = this.getFormControls();
|
||||
const formControlsThatReport = formControls.filter((el: any) => typeof el.reportValidity === 'function') as any;
|
||||
|
||||
if (!this.novalidate) {
|
||||
for (const el of formControlsThatReport) {
|
||||
const isValid = el.reportValidity();
|
||||
|
||||
if (!isValid) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
emit(this, 'sl-submit', { detail: { formData, formControls } });
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
handleClick(event: MouseEvent) {
|
||||
const target = event.target as HTMLElement;
|
||||
const tag = target.tagName.toLowerCase();
|
||||
|
||||
for (const formControl of this.formControls) {
|
||||
if (formControl.tag === tag && formControl.click) {
|
||||
formControl.click(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handleKeyDown(event: KeyboardEvent) {
|
||||
const target = event.target as HTMLElement;
|
||||
const tag = target.tagName.toLowerCase();
|
||||
|
||||
for (const formControl of this.formControls) {
|
||||
if (formControl.tag === tag && formControl.keyDown) {
|
||||
formControl.keyDown(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
serializeElement(el: HTMLElement, formData: FormData) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
|
||||
for (const formControl of this.formControls) {
|
||||
if (formControl.tag === tag) {
|
||||
return formControl.serialize(el, formData);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<div part="base" class="form" role="form" @click=${this.handleClick} @keydown=${this.handleKeyDown}>
|
||||
<slot></slot>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'sl-form': SlForm;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { classMap } from 'lit/directives/class-map.js';
|
||||
import { live } from 'lit/directives/live.js';
|
||||
import { emit } from '../../internal/event';
|
||||
import { watch } from '../../internal/watch';
|
||||
import { getLabelledBy, renderFormControl } from '../../internal/form-control';
|
||||
import { FormSubmitController, getLabelledBy, renderFormControl } from '../../internal/form-control';
|
||||
import { HasSlotController } from '../../internal/slot';
|
||||
import styles from './input.styles';
|
||||
|
||||
@@ -49,6 +49,8 @@ export default class SlInput extends LitElement {
|
||||
|
||||
@query('.input__control') input: HTMLInputElement;
|
||||
|
||||
// @ts-ignore
|
||||
private formSubmitController = new FormSubmitController(this);
|
||||
private hasSlotController = new HasSlotController(this, 'help-text', 'label');
|
||||
private inputId = `input-${++id}`;
|
||||
private helpTextId = `input-help-text-${id}`;
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ifDefined } from 'lit/directives/if-defined.js';
|
||||
import { live } from 'lit/directives/live.js';
|
||||
import { emit } from '../../internal/event';
|
||||
import { watch } from '../../internal/watch';
|
||||
import { FormSubmitController } from '../../internal/form-control';
|
||||
import styles from './radio.styles';
|
||||
|
||||
/**
|
||||
@@ -28,6 +29,11 @@ export default class SlRadio extends LitElement {
|
||||
|
||||
@query('input[type="radio"]') input: HTMLInputElement;
|
||||
|
||||
// @ts-ignore
|
||||
private formSubmitController = new FormSubmitController(this, {
|
||||
value: (control: SlRadio) => (control.checked ? control.value : undefined)
|
||||
});
|
||||
|
||||
@state() private hasFocus = false;
|
||||
|
||||
/** The radio's name attribute. */
|
||||
|
||||
@@ -6,6 +6,7 @@ import { emit } from '../../internal/event';
|
||||
import { live } from 'lit/directives/live.js';
|
||||
import { watch } from '../../internal/watch';
|
||||
import { getLabelledBy, renderFormControl } from '../../internal/form-control';
|
||||
import { FormSubmitController } from '../../internal/form-control';
|
||||
import { HasSlotController } from '../../internal/slot';
|
||||
import styles from './range.styles';
|
||||
|
||||
@@ -39,6 +40,8 @@ export default class SlRange extends LitElement {
|
||||
@query('.range__control') input: HTMLInputElement;
|
||||
@query('.range__tooltip') output: HTMLOutputElement;
|
||||
|
||||
// @ts-ignore
|
||||
private formSubmitController = new FormSubmitController(this);
|
||||
private hasSlotController = new HasSlotController(this, 'help-text', 'label');
|
||||
private inputId = `input-${++id}`;
|
||||
private helpTextId = `input-help-text-${id}`;
|
||||
|
||||
@@ -6,6 +6,7 @@ import { emit } from '../../internal/event';
|
||||
import { watch } from '../../internal/watch';
|
||||
import { getLabelledBy, renderFormControl } from '../../internal/form-control';
|
||||
import { getTextContent } from '../../internal/slot';
|
||||
import { FormSubmitController } from '../../internal/form-control';
|
||||
import { HasSlotController } from '../../internal/slot';
|
||||
import type SlDropdown from '../dropdown/dropdown';
|
||||
import type SlIconButton from '../icon-button/icon-button';
|
||||
@@ -65,6 +66,8 @@ export default class SlSelect extends LitElement {
|
||||
@query('.select__hidden-select') input: HTMLInputElement;
|
||||
@query('.select__menu') menu: SlMenu;
|
||||
|
||||
// @ts-ignore
|
||||
private formSubmitController = new FormSubmitController(this);
|
||||
private hasSlotController = new HasSlotController(this, 'help-text', 'label');
|
||||
private inputId = `select-${++id}`;
|
||||
private helpTextId = `select-help-text-${id}`;
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ifDefined } from 'lit/directives/if-defined.js';
|
||||
import { live } from 'lit/directives/live.js';
|
||||
import { emit } from '../../internal/event';
|
||||
import { watch } from '../../internal/watch';
|
||||
import { FormSubmitController } from '../../internal/form-control';
|
||||
import styles from './switch.styles';
|
||||
|
||||
let id = 0;
|
||||
@@ -34,6 +35,10 @@ export default class SlSwitch extends LitElement {
|
||||
|
||||
@query('input[type="checkbox"]') input: HTMLInputElement;
|
||||
|
||||
// @ts-ignore
|
||||
private formSubmitController = new FormSubmitController(this, {
|
||||
value: (control: SlSwitch) => (control.checked ? control.value : undefined)
|
||||
});
|
||||
private switchId = `switch-${++id}`;
|
||||
private labelId = `switch-label-${id}`;
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { emit } from '../../internal/event';
|
||||
import { live } from 'lit/directives/live.js';
|
||||
import { watch } from '../../internal/watch';
|
||||
import { getLabelledBy, renderFormControl } from '../../internal/form-control';
|
||||
import { FormSubmitController } from '../../internal/form-control';
|
||||
import { HasSlotController } from '../../internal/slot';
|
||||
import styles from './textarea.styles';
|
||||
|
||||
@@ -35,6 +36,8 @@ export default class SlTextarea extends LitElement {
|
||||
|
||||
@query('.textarea__control') input: HTMLTextAreaElement;
|
||||
|
||||
// @ts-ignore
|
||||
private formSubmitController = new FormSubmitController(this);
|
||||
private hasSlotController = new HasSlotController(this, 'help-text', 'label');
|
||||
private inputId = `textarea-${++id}`;
|
||||
private helpTextId = `textarea-help-text-${id}`;
|
||||
|
||||
@@ -1,6 +1,108 @@
|
||||
import { html, TemplateResult } from 'lit';
|
||||
import { html, ReactiveController, ReactiveControllerHost, TemplateResult } from 'lit';
|
||||
import { classMap } from 'lit/directives/class-map.js';
|
||||
import { ifDefined } from 'lit/directives/if-defined.js';
|
||||
import './formdata-event-polyfill';
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
submit() {
|
||||
// Calling form.submit() seems to bypass the submit event and constraint validation. Instead, we can inject a
|
||||
// native submit button into the form, click it, then remove it to simulate a standard form submission.
|
||||
const button = document.createElement('button');
|
||||
if (this.form) {
|
||||
button.type = 'submit';
|
||||
button.style.position = 'absolute';
|
||||
button.style.width = '0';
|
||||
button.style.height = '0';
|
||||
button.style.clip = 'rect(0 0 0 0)';
|
||||
button.style.clipPath = 'inset(50%)';
|
||||
button.style.overflow = 'hidden';
|
||||
button.style.whiteSpace = 'nowrap';
|
||||
this.form.append(button);
|
||||
button.click();
|
||||
button.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const renderFormControl = (
|
||||
props: {
|
||||
|
||||
93
src/internal/formdata-event-polyfill.ts
Normal file
93
src/internal/formdata-event-polyfill.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
//
|
||||
// Polyfills the formdata event in unsupportive browsers. This is a partial polyfill to support appending custom element
|
||||
// form data on submit. The formdata event landed in Safari until 15.1, which is slighly too new to rely on. All other
|
||||
// browsers have great support.
|
||||
//
|
||||
// https://caniuse.com/mdn-api_htmlformelement_formdata_event
|
||||
//
|
||||
// Original code derived from: https://gist.github.com/WickyNilliams/eb6a44075356ee504dd9491c5a3ab0be
|
||||
//
|
||||
// Copyright (c) 2021 Nick Williams (https://wicky.nillia.ms)
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
class FormDataEventPolyfill extends Event {
|
||||
formData: FormData;
|
||||
|
||||
constructor(formData: FormData) {
|
||||
super('formdata');
|
||||
this.formData = formData;
|
||||
}
|
||||
}
|
||||
|
||||
class FormDataPolyfill extends FormData {
|
||||
private form: HTMLFormElement;
|
||||
|
||||
constructor(form: HTMLFormElement) {
|
||||
super(form);
|
||||
this.form = form;
|
||||
form.dispatchEvent(new FormDataEventPolyfill(this));
|
||||
}
|
||||
|
||||
append(name: string, value: any) {
|
||||
let input = this.form.elements[name as any] as HTMLInputElement;
|
||||
|
||||
if (!input) {
|
||||
input = document.createElement('input');
|
||||
input.type = 'hidden';
|
||||
input.name = name;
|
||||
this.form.appendChild(input);
|
||||
}
|
||||
|
||||
if (this.has(name)) {
|
||||
const entries = this.getAll(name);
|
||||
const index = entries.indexOf(input.value);
|
||||
|
||||
if (index !== -1) {
|
||||
entries.splice(index, 1);
|
||||
}
|
||||
|
||||
entries.push(value);
|
||||
this.set(name, entries as any);
|
||||
} else {
|
||||
super.append(name, value);
|
||||
}
|
||||
|
||||
input.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
function supportsFormDataEvent() {
|
||||
const form = document.createElement('form');
|
||||
let isSupported = false;
|
||||
|
||||
document.body.append(form);
|
||||
|
||||
form.addEventListener('submit', event => {
|
||||
new FormData(event.target as HTMLFormElement);
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
form.addEventListener('formdata', () => (isSupported = true));
|
||||
form.dispatchEvent(new Event('submit', { cancelable: true }));
|
||||
form.remove();
|
||||
|
||||
return isSupported;
|
||||
}
|
||||
|
||||
function polyfillFormData() {
|
||||
if (!window.FormData || supportsFormDataEvent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.FormData = FormDataPolyfill;
|
||||
window.addEventListener('submit', event => {
|
||||
if (!event.defaultPrevented) {
|
||||
new FormData(event.target as HTMLFormElement);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
polyfillFormData();
|
||||
@@ -16,7 +16,6 @@ export { default as SlDialog } from './components/dialog/dialog';
|
||||
export { default as SlDivider } from './components/divider/divider';
|
||||
export { default as SlDrawer } from './components/drawer/drawer';
|
||||
export { default as SlDropdown } from './components/dropdown/dropdown';
|
||||
export { default as SlForm } from './components/form/form';
|
||||
export { default as SlFormatBytes } from './components/format-bytes/format-bytes';
|
||||
export { default as SlFormatDate } from './components/format-date/format-date';
|
||||
export { default as SlFormatNumber } from './components/format-number/format-number';
|
||||
|
||||
22
src/utilities/form.ts
Normal file
22
src/utilities/form.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
//
|
||||
// Serializes a form and returns a plain object. If a form control with the same name appears more than once, the
|
||||
// property will be converted to an array.
|
||||
//
|
||||
export function serialize(form: HTMLFormElement) {
|
||||
const formData = new FormData(form);
|
||||
const object: { [key: string]: any } = {};
|
||||
|
||||
formData.forEach((value, key) => {
|
||||
if (Reflect.has(object, key)) {
|
||||
if (Array.isArray(object[key])) {
|
||||
object[key].push(value);
|
||||
} else {
|
||||
object[key] = [object[key], value];
|
||||
}
|
||||
} else {
|
||||
object[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
return object;
|
||||
}
|
||||
Reference in New Issue
Block a user