lib/widgets/dialog/Dialog.js

import $ from 'jquery'
import { j3pAddElt, j3pDetruit } from 'src/legacy/core/functions'

class Dialog {
  /**
   * Boite de dialogue jQuery
   * Il faut avoir attendu la résolution de loadJqueryDialog() avant d’en créer
   * @param {Object} [options] Les options passées à la méthode jQuery dialog à la création {@link https://api.jqueryui.com/dialog/}
   * @param {string} [options.title]
   * @param {number} [options.width]
   * @param {number} [options.height]
   * @param {number} [options.maxWidth]
   * @param {number} [options.maxHeight]
   */
  constructor (options = {}) {
    if (!$?.ui) throw Error('Il faut appeler loadJqueryDialog() avant de créer des objets Dialog')
    // on le met dans body car de toute manière jQuery.dialog le mettra enfant direct de body
    /**
     * Le div du contenu de la boîte de dialogue
     * @type {HTMLElement}
     */
    this.container = j3pAddElt(document.body, 'div', '', {
      className: 'dialog',
      title: options.title || ''
    })

    // options de la boite de dialogue
    const dialogOptions = {
      autoOpen: false,
      resizable: false,
      ...options,
      title: undefined // déjà utilisé s’il était présent
    }
    // on impose ça si on ne l’a pas fourni
    if (!dialogOptions.height && !dialogOptions.maxHeight) dialogOptions.maxHeight = 500
    this.$dialog = $(this.container).dialog(dialogOptions)
  }

  toggle () {
    if (!this.$dialog) return console.error(Error('Cette boite de dialogue a déjà été détruite'))
    if (this.$dialog.dialog('isOpen')) this.$dialog.dialog('close')
    else this.$dialog.dialog('open')
  }

  show () {
    if (!this.$dialog) return console.error(Error('Cette boite de dialogue a déjà été détruite'))
    if (!this.$dialog.dialog('isOpen')) this.$dialog.dialog('open')
  }

  hide () {
    if (!this.$dialog) return console.error(Error('Cette boite de dialogue a déjà été détruite'))
    if (this.$dialog.dialog('isOpen')) this.$dialog.dialog('close')
  }

  destroy () {
    if (!this.$dialog) return console.error(Error('Cette boite de dialogue a déjà été détruite'))
    this.$dialog.dialog('destroy')
    j3pDetruit(this.container)
    this.container = null
    this.$dialog = null
  }
}

export default Dialog