lion icon indicating copy to clipboard operation
lion copied to clipboard

<lion-button> should support form attribute

Open lpoulter opened this issue 2 years ago • 1 comments

Expected behavior

I would expect <lion-button> to support native button attributes. When I supply a form attribute to a button component outside a <form> it should submit the form.

Actual Behavior

The form is not submitted.

lpoulter avatar Aug 26 '21 11:08 lpoulter

Hi,

Makes sense to add this for LionButtonReset and LionButtonSubmit (that are designed to be compatible with the native form).

We could do something like this inside LionButtonReset:

static get properties() {
  return {
    ...
    // Native button has attr type string, and prop type HTMLFormElement. We keep both string, and keep the HTMLFormElement in _form
    form: { type: String }
  }
}

updated(changedProperties) {
  super.updated(changedProperties);

  if(changedProperties.has('form')) {
      // This will make the platform find the form and add it to this._form inside _setupSubmitAndResetHelper
      this.__submitAndResetHelperButton.setAttribute('form', typeof this.form === 'string' ? this.form : '');

     // remove prev event handlers if we change form ref
     const newForm = this.__submitAndResetHelperButton.form;
     if (this._form !== newForm) {
       this._teardownSubmitAndResetHelper();
     }
     this._setupSubmitAndResetHelper();
  }
}

  /**
   * @protected
   */
  _setupSubmitAndResetHelperOnConnected() {
    this._setupSubmitAndResetHelper();
  }

  /**
   * @protected
   */
  _setupSubmitAndResetHelper() {
    // Get form
    this.appendChild(this.__submitAndResetHelperButton);
    /** @type {HTMLFormElement|null} */
    this._form = this.__submitAndResetHelperButton.form;
    this.removeChild(this.__submitAndResetHelperButton);

    if (this._form) {
      this._form.addEventListener('click', this.__preventEventLeakage);
    }
  }
  
    /**
   * @protected
   */
  _teardownSubmitAndResetHelperOnDisconnected() {
    this. _teardownSubmitAndResetHelper();
  }
  
  _teardownSubmitAndResetHelper() {
   if (this._form) {
      this._form.removeEventListener('click', this.__preventEventLeakage);
    }
  }


Let us know if you're interested in doing a PR for this :)

tlouisse avatar Aug 27 '21 12:08 tlouisse