toast.js 12.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
import { Portal, Wormhole } from 'portal-vue'
import { COMPONENT_UID_KEY, extend } from '../../vue'
import { NAME_TOAST, NAME_TOASTER } from '../../constants/components'
import {
  EVENT_NAME_CHANGE,
  EVENT_NAME_DESTROYED,
  EVENT_NAME_HIDDEN,
  EVENT_NAME_HIDE,
  EVENT_NAME_SHOW,
  EVENT_NAME_SHOWN,
  EVENT_OPTIONS_NO_CAPTURE
} from '../../constants/events'
import {
  PROP_TYPE_ARRAY_OBJECT_STRING,
  PROP_TYPE_BOOLEAN,
  PROP_TYPE_NUMBER_STRING,
  PROP_TYPE_STRING
} from '../../constants/props'
import { SLOT_NAME_DEFAULT, SLOT_NAME_TOAST_TITLE } from '../../constants/slots'
import { BvEvent } from '../../utils/bv-event.class'
import { requestAF } from '../../utils/dom'
import { getRootActionEventName, getRootEventName, eventOnOff } from '../../utils/events'
import { mathMax } from '../../utils/math'
import { makeModelMixin } from '../../utils/model'
import { toInteger } from '../../utils/number'
import { pick, sortKeys } from '../../utils/object'
import { makeProp, makePropsConfigurable, pluckProps } from '../../utils/props'
import { isLink } from '../../utils/router'
import { createNewChildComponent } from '../../utils/create-new-child-component'
import { attrsMixin } from '../../mixins/attrs'
import { idMixin, props as idProps } from '../../mixins/id'
import { listenOnRootMixin } from '../../mixins/listen-on-root'
import { normalizeSlotMixin } from '../../mixins/normalize-slot'
import { scopedStyleMixin } from '../../mixins/scoped-style'
import { BButtonClose } from '../button/button-close'
import { BLink, props as BLinkProps } from '../link/link'
import { BVTransition } from '../transition/bv-transition'
import { BToaster } from './toaster'

// --- Constants ---

const {
  mixin: modelMixin,
  props: modelProps,
  prop: MODEL_PROP_NAME,
  event: MODEL_EVENT_NAME
} = makeModelMixin('visible', {
  type: PROP_TYPE_BOOLEAN,
  defaultValue: false,
  event: EVENT_NAME_CHANGE
})

const MIN_DURATION = 1000

// --- Props ---

const linkProps = pick(BLinkProps, ['href', 'to'])

export const props = makePropsConfigurable(
  sortKeys({
    ...idProps,
    ...modelProps,
    ...linkProps,
    appendToast: makeProp(PROP_TYPE_BOOLEAN, false),
    autoHideDelay: makeProp(PROP_TYPE_NUMBER_STRING, 5000),
    bodyClass: makeProp(PROP_TYPE_ARRAY_OBJECT_STRING),
    headerClass: makeProp(PROP_TYPE_ARRAY_OBJECT_STRING),
    headerTag: makeProp(PROP_TYPE_STRING, 'header'),
    // Switches role to 'status' and aria-live to 'polite'
    isStatus: makeProp(PROP_TYPE_BOOLEAN, false),
    noAutoHide: makeProp(PROP_TYPE_BOOLEAN, false),
    noCloseButton: makeProp(PROP_TYPE_BOOLEAN, false),
    noFade: makeProp(PROP_TYPE_BOOLEAN, false),
    noHoverPause: makeProp(PROP_TYPE_BOOLEAN, false),
    solid: makeProp(PROP_TYPE_BOOLEAN, false),
    // Render the toast in place, rather than in a portal-target
    static: makeProp(PROP_TYPE_BOOLEAN, false),
    title: makeProp(PROP_TYPE_STRING),
    toastClass: makeProp(PROP_TYPE_ARRAY_OBJECT_STRING),
    toaster: makeProp(PROP_TYPE_STRING, 'b-toaster-top-right'),
    variant: makeProp(PROP_TYPE_STRING)
  }),
  NAME_TOAST
)

// --- Main component ---

// @vue/component
export const BToast = /*#__PURE__*/ extend({
  name: NAME_TOAST,
  mixins: [
    attrsMixin,
    idMixin,
    modelMixin,
    listenOnRootMixin,
    normalizeSlotMixin,
    scopedStyleMixin
  ],
  inheritAttrs: false,
  props,
  data() {
    return {
      isMounted: false,
      doRender: false,
      localShow: false,
      isTransitioning: false,
      isHiding: false,
      order: 0,
      dismissStarted: 0,
      resumeDismiss: 0
    }
  },
  computed: {
    toastClasses() {
      const { appendToast, variant } = this

      return {
        'b-toast-solid': this.solid,
        'b-toast-append': appendToast,
        'b-toast-prepend': !appendToast,
        [`b-toast-${variant}`]: variant
      }
    },
    slotScope() {
      const { hide } = this
      return { hide }
    },
    computedDuration() {
      // Minimum supported duration is 1 second
      return mathMax(toInteger(this.autoHideDelay, 0), MIN_DURATION)
    },
    computedToaster() {
      return String(this.toaster)
    },
    transitionHandlers() {
      return {
        beforeEnter: this.onBeforeEnter,
        afterEnter: this.onAfterEnter,
        beforeLeave: this.onBeforeLeave,
        afterLeave: this.onAfterLeave
      }
    },
    computedAttrs() {
      return {
        ...this.bvAttrs,
        id: this.safeId(),
        tabindex: '0'
      }
    }
  },
  watch: {
    [MODEL_PROP_NAME](newValue) {
      this[newValue ? 'show' : 'hide']()
    },
    localShow(newValue) {
      if (newValue !== this[MODEL_PROP_NAME]) {
        this.$emit(MODEL_EVENT_NAME, newValue)
      }
    },
    /* istanbul ignore next */
    toaster() {
      // If toaster target changed, make sure toaster exists
      this.$nextTick(this.ensureToaster)
    },
    /* istanbul ignore next */
    static(newValue) {
      // If static changes to true, and the toast is showing,
      // ensure the toaster target exists
      if (newValue && this.localShow) {
        this.ensureToaster()
      }
    }
  },
  created() {
    // Create private non-reactive props
    this.$_dismissTimer = null
  },
  mounted() {
    this.isMounted = true
    this.$nextTick(() => {
      if (this[MODEL_PROP_NAME]) {
        requestAF(() => {
          this.show()
        })
      }
    })
    // Listen for global $root show events
    this.listenOnRoot(getRootActionEventName(NAME_TOAST, EVENT_NAME_SHOW), id => {
      if (id === this.safeId()) {
        this.show()
      }
    })
    // Listen for global $root hide events
    this.listenOnRoot(getRootActionEventName(NAME_TOAST, EVENT_NAME_HIDE), id => {
      if (!id || id === this.safeId()) {
        this.hide()
      }
    })
    // Make sure we hide when toaster is destroyed
    /* istanbul ignore next: difficult to test */
    this.listenOnRoot(getRootEventName(NAME_TOASTER, EVENT_NAME_DESTROYED), toaster => {
      /* istanbul ignore next */
      if (toaster === this.computedToaster) {
        this.hide()
      }
    })
  },
  beforeDestroy() {
    this.clearDismissTimer()
  },
  methods: {
    show() {
      if (!this.localShow) {
        this.ensureToaster()
        const showEvent = this.buildEvent(EVENT_NAME_SHOW)
        this.emitEvent(showEvent)
        this.dismissStarted = this.resumeDismiss = 0
        this.order = Date.now() * (this.appendToast ? 1 : -1)
        this.isHiding = false
        this.doRender = true
        this.$nextTick(() => {
          // We show the toast after we have rendered the portal and b-toast wrapper
          // so that screen readers will properly announce the toast
          requestAF(() => {
            this.localShow = true
          })
        })
      }
    },
    hide() {
      if (this.localShow) {
        const hideEvent = this.buildEvent(EVENT_NAME_HIDE)
        this.emitEvent(hideEvent)
        this.setHoverHandler(false)
        this.dismissStarted = this.resumeDismiss = 0
        this.clearDismissTimer()
        this.isHiding = true
        requestAF(() => {
          this.localShow = false
        })
      }
    },
    buildEvent(type, options = {}) {
      return new BvEvent(type, {
        cancelable: false,
        target: this.$el || null,
        relatedTarget: null,
        ...options,
        vueTarget: this,
        componentId: this.safeId()
      })
    },
    emitEvent(bvEvent) {
      const { type } = bvEvent
      this.emitOnRoot(getRootEventName(NAME_TOAST, type), bvEvent)
      this.$emit(type, bvEvent)
    },
    ensureToaster() {
      if (this.static) {
        return
      }

      const { computedToaster } = this
      if (!Wormhole.hasTarget(computedToaster)) {
        const div = document.createElement('div')
        document.body.appendChild(div)

        const toaster = createNewChildComponent(this.bvEventRoot, BToaster, {
          propsData: { name: computedToaster }
        })

        toaster.$mount(div)
      }
    },
    startDismissTimer() {
      this.clearDismissTimer()
      if (!this.noAutoHide) {
        this.$_dismissTimer = setTimeout(this.hide, this.resumeDismiss || this.computedDuration)
        this.dismissStarted = Date.now()
        this.resumeDismiss = 0
      }
    },
    clearDismissTimer() {
      clearTimeout(this.$_dismissTimer)
      this.$_dismissTimer = null
    },
    setHoverHandler(on) {
      const el = this.$refs['b-toast']
      eventOnOff(on, el, 'mouseenter', this.onPause, EVENT_OPTIONS_NO_CAPTURE)
      eventOnOff(on, el, 'mouseleave', this.onUnPause, EVENT_OPTIONS_NO_CAPTURE)
    },
    onPause() {
      // Determine time remaining, and then pause timer
      if (this.noAutoHide || this.noHoverPause || !this.$_dismissTimer || this.resumeDismiss) {
        return
      }
      const passed = Date.now() - this.dismissStarted
      if (passed > 0) {
        this.clearDismissTimer()
        this.resumeDismiss = mathMax(this.computedDuration - passed, MIN_DURATION)
      }
    },
    onUnPause() {
      // Restart timer with max of time remaining or 1 second
      if (this.noAutoHide || this.noHoverPause || !this.resumeDismiss) {
        this.resumeDismiss = this.dismissStarted = 0
        return
      }
      this.startDismissTimer()
    },
    onLinkClick() {
      // We delay the close to allow time for the
      // browser to process the link click
      this.$nextTick(() => {
        requestAF(() => {
          this.hide()
        })
      })
    },
    onBeforeEnter() {
      this.isTransitioning = true
    },
    onAfterEnter() {
      this.isTransitioning = false
      const hiddenEvent = this.buildEvent(EVENT_NAME_SHOWN)
      this.emitEvent(hiddenEvent)
      this.startDismissTimer()
      this.setHoverHandler(true)
    },
    onBeforeLeave() {
      this.isTransitioning = true
    },
    onAfterLeave() {
      this.isTransitioning = false
      this.order = 0
      this.resumeDismiss = this.dismissStarted = 0
      const hiddenEvent = this.buildEvent(EVENT_NAME_HIDDEN)
      this.emitEvent(hiddenEvent)
      this.doRender = false
    },
    // Render helper for generating the toast
    makeToast(h) {
      const { title, slotScope } = this
      const link = isLink(this)
      const $headerContent = []

      const $title = this.normalizeSlot(SLOT_NAME_TOAST_TITLE, slotScope)
      if ($title) {
        $headerContent.push($title)
      } else if (title) {
        $headerContent.push(h('strong', { staticClass: 'mr-2' }, title))
      }

      if (!this.noCloseButton) {
        $headerContent.push(
          h(BButtonClose, {
            staticClass: 'ml-auto mb-1',
            on: {
              click: () => {
                this.hide()
              }
            }
          })
        )
      }

      let $header = h()
      if ($headerContent.length > 0) {
        $header = h(
          this.headerTag,
          {
            staticClass: 'toast-header',
            class: this.headerClass
          },
          $headerContent
        )
      }

      const $body = h(
        link ? BLink : 'div',
        {
          staticClass: 'toast-body',
          class: this.bodyClass,
          props: link ? pluckProps(linkProps, this) : {},
          on: link ? { click: this.onLinkClick } : {}
        },
        this.normalizeSlot(SLOT_NAME_DEFAULT, slotScope)
      )

      return h(
        'div',
        {
          staticClass: 'toast',
          class: this.toastClass,
          attrs: this.computedAttrs,
          key: `toast-${this[COMPONENT_UID_KEY]}`,
          ref: 'toast'
        },
        [$header, $body]
      )
    }
  },
  render(h) {
    if (!this.doRender || !this.isMounted) {
      return h()
    }

    const { order, static: isStatic, isHiding, isStatus } = this
    const name = `b-toast-${this[COMPONENT_UID_KEY]}`

    const $toast = h(
      'div',
      {
        staticClass: 'b-toast',
        class: this.toastClasses,
        attrs: {
          // If scoped styles are applied and the toast is not static,
          // make sure the scoped style data attribute is applied
          ...(isStatic ? {} : this.scopedStyleAttrs),
          id: this.safeId('_toast_outer'),
          role: isHiding ? null : isStatus ? 'status' : 'alert',
          'aria-live': isHiding ? null : isStatus ? 'polite' : 'assertive',
          'aria-atomic': isHiding ? null : 'true'
        },
        key: name,
        ref: 'b-toast'
      },
      [
        h(
          BVTransition,
          {
            props: { noFade: this.noFade },
            on: this.transitionHandlers
          },
          [this.localShow ? this.makeToast(h) : h()]
        )
      ]
    )

    return h(
      Portal,
      {
        props: {
          name,
          to: this.computedToaster,
          order,
          slim: true,
          disabled: isStatic
        }
      },
      [$toast]
    )
  }
})