robinparisi / tingle

⚡ 2kB vanilla modal plugin, no dependencies and easy-to-use
https://tingle.robinparisi.com
MIT License
1.56k stars 184 forks source link

Reason for close #169

Open joho1968 opened 3 years ago

joho1968 commented 3 years ago

It'd be nice if Tingle could somehow signal how it was closed, i.e. by a click outside, the escape key, a click on the close button and so on. An application may want to handle this differently.

joho1968 commented 3 years ago

Maybe something along these lines ...

[new]

  const tingleCloseNone = 0;
  const tingleCloseKeyboard = 1;
  const tingleCloseButton = 2;
  const tingleCloseClickOutside = 3;

  var _reasonForClose = tingleCloseNone;

  Modal.prototype.reasonForClose = function () {
    return this._reasonForClose;
  }

[modify]

  function _handleKeyboardNav (event) {
    // escape key
    if (this.opts.closeMethods.indexOf('escape') !== -1 && event.which === 27 && this.isOpen()) {
      this._reasonForClose = tingleCloseKeyboard;/*new*/
      this.close()
    }
  }

  function _handleClickOutside (event) {
    // on macOS, click on scrollbar (hidden mode) will trigger close event so we need to bypass this behavior by detecting scrollbar mode
    var scrollbarWidth = this.modal.offsetWidth - this.modal.clientWidth
    var clickedOnScrollbar = event.clientX >= this.modal.offsetWidth - 15 // 15px is macOS scrollbar default width
    var isScrollable = this.modal.scrollHeight !== this.modal.offsetHeight
    if (navigator.platform === 'MacIntel' && scrollbarWidth === 0 && clickedOnScrollbar && isScrollable) {
      return
    }

    // if click is outside the modal
    if (this.opts.closeMethods.indexOf('overlay') !== -1 && !_findAncestor(event.target, 'tingle-modal') &&
        event.clientX < this.modal.clientWidth) {
      this._reasonForClose = tingleCloseClickOutside;/*new*/
      this.close()
    }
  }

I guess Modal.prototype.close = function (force) {} also needs to be modified so that:

if (this.reasonForClose == tingleCloseNone) {
  this._reasonForClose = tingleCloseButton;
}