tab-nav.vue 10.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
<script>
import TabBar from "./tab-bar"
const resizeHandler = function (entries) {
  for (let entry of entries) {
    const listeners = entry.target.__resizeListeners__ || []
    if (listeners.length) {
      listeners.forEach((fn) => {
        fn()
      })
    }
  }
}
const addResizeListener = function (element, fn) {
  if (!element.__resizeListeners__) {
    element.__resizeListeners__ = []
    element.__ro__ = new ResizeObserver(resizeHandler)
    element.__ro__.observe(element)
  }
  element.__resizeListeners__.push(fn)
}

const removeResizeListener = function (element, fn) {
  if (!element || !element.__resizeListeners__) return
  element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1)
  if (!element.__resizeListeners__.length) {
    element.__ro__?.disconnect()
  }
}

function noop() {}
const firstUpperCase = (str) => {
  return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
}
import draggable from "vuedraggable"
export default {
  name: "TabNav",

  components: {
    TabBar,
    draggable
  },

  inject: ["rootTabs"],

  props: {
    tabListItem: Array,
    panes: Array,
    currentName: String,
    editable: Boolean,
    onTabClick: {
      type: Function,
      default: noop
    },
    onTabEdit: {
      type: Function,
      default: noop
    },
    onTabRemove: {
      type: Function,
      default: noop
    },
    type: String,
    stretch: Boolean
  },

  data() {
    return {
      scrollable: false,
      navOffset: 0,
      isFocus: false,
      focusable: true
    }
  },

  computed: {
    navStyle() {
      const dir =
        ["top", "bottom"].indexOf(this.rootTabs.tabPosition) !== -1 ? "X" : "Y"
      return {
        transform: `translate${dir}(-${this.navOffset}px)`
      }
    },
    sizeName() {
      return ["top", "bottom"].indexOf(this.rootTabs.tabPosition) !== -1
        ? "width"
        : "height"
    }
  },

  methods: {
    dragEnd(e) {
      if (e.oldIndex != e.newIndex) {
        const idx = this.tabListItem[e.newIndex]
        this.$set(this.tabListItem, e.newIndex, this.tabListItem[e.oldIndex])
        this.$set(this.tabListItem, e.oldIndex, idx)
      }
    },
    scrollPrev() {
      const containerSize =
        this.$refs.navScroll[`offset${firstUpperCase(this.sizeName)}`]
      const currentOffset = this.navOffset

      if (!currentOffset) return

      let newOffset =
        currentOffset > containerSize ? currentOffset - containerSize : 0

      this.navOffset = newOffset
    },
    scrollNext() {
      const navSize = this.$refs.nav[`offset${firstUpperCase(this.sizeName)}`]
      const containerSize =
        this.$refs.navScroll[`offset${firstUpperCase(this.sizeName)}`]
      const currentOffset = this.navOffset

      if (navSize - currentOffset <= containerSize) return

      let newOffset =
        navSize - currentOffset > containerSize * 2
          ? currentOffset + containerSize
          : navSize - containerSize

      this.navOffset = newOffset
    },
    scrollToActiveTab() {
      if (!this.scrollable) return
      const nav = this.$refs.nav
      const activeTab = this.$el.querySelector(".is-active")
      if (!activeTab) return
      const navScroll = this.$refs.navScroll
      const isHorizontal =
        ["top", "bottom"].indexOf(this.rootTabs.tabPosition) !== -1
      const activeTabBounding = activeTab.getBoundingClientRect()
      const navScrollBounding = navScroll.getBoundingClientRect()
      const maxOffset = isHorizontal
        ? nav.offsetWidth - navScrollBounding.width
        : nav.offsetHeight - navScrollBounding.height
      const currentOffset = this.navOffset
      let newOffset = currentOffset

      if (isHorizontal) {
        if (activeTabBounding.left < navScrollBounding.left) {
          newOffset =
            currentOffset - (navScrollBounding.left - activeTabBounding.left)
        }
        if (activeTabBounding.right > navScrollBounding.right) {
          newOffset =
            currentOffset + activeTabBounding.right - navScrollBounding.right
        }
      } else {
        if (activeTabBounding.top < navScrollBounding.top) {
          newOffset =
            currentOffset - (navScrollBounding.top - activeTabBounding.top)
        }
        if (activeTabBounding.bottom > navScrollBounding.bottom) {
          newOffset =
            currentOffset +
            (activeTabBounding.bottom - navScrollBounding.bottom)
        }
      }
      newOffset = Math.max(newOffset, 0)
      this.navOffset = Math.min(newOffset, maxOffset)
    },
    update() {
      if (!this.$refs.nav) return
      const sizeName = this.sizeName
      const navSize = this.$refs.nav[`offset${firstUpperCase(sizeName)}`]
      const containerSize =
        this.$refs.navScroll[`offset${firstUpperCase(sizeName)}`]
      const currentOffset = this.navOffset

      if (containerSize < navSize) {
        const currentOffset = this.navOffset
        this.scrollable = this.scrollable || {}
        this.scrollable.prev = currentOffset
        this.scrollable.next = currentOffset + containerSize < navSize
        if (navSize - currentOffset < containerSize) {
          this.navOffset = navSize - containerSize
        }
      } else {
        this.scrollable = false
        if (currentOffset > 0) {
          this.navOffset = 0
        }
      }
    },
    changeTab(e) {
      const keyCode = e.keyCode
      let nextIndex
      let currentIndex, tabList
      if ([37, 38, 39, 40].indexOf(keyCode) !== -1) {
        // 左右上下键更换tab
        tabList = e.currentTarget.querySelectorAll("[role=tab]")
        currentIndex = Array.prototype.indexOf.call(tabList, e.target)
      } else {
        return
      }
      if (keyCode === 37 || keyCode === 38) {
        // left
        if (currentIndex === 0) {
          // first
          nextIndex = tabList.length - 1
        } else {
          nextIndex = currentIndex - 1
        }
      } else {
        // right
        if (currentIndex < tabList.length - 1) {
          // not last
          nextIndex = currentIndex + 1
        } else {
          nextIndex = 0
        }
      }
      tabList[nextIndex].focus() // 改变焦点元素
      tabList[nextIndex].click() // 选中下一个tab
      this.setFocus()
    },
    setFocus() {
      if (this.focusable) {
        this.isFocus = true
      }
    },
    removeFocus() {
      this.isFocus = false
    },
    visibilityChangeHandler() {
      const visibility = document.visibilityState
      if (visibility === "hidden") {
        this.focusable = false
      } else if (visibility === "visible") {
        setTimeout(() => {
          this.focusable = true
        }, 50)
      }
    },
    windowBlurHandler() {
      this.focusable = false
    },
    windowFocusHandler() {
      setTimeout(() => {
        this.focusable = true
      }, 50)
    }
  },

  updated() {
    this.update()
  },

  render(h) {
    const {
      type,
      panes,
      editable,
      stretch,
      onTabClick,
      onTabRemove,
      navStyle,
      scrollable,
      scrollNext,
      scrollPrev,
      changeTab,
      setFocus,
      removeFocus,
      dragEnd,
      tabListItem,
      onTabEdit
    } = this
    const scrollBtn = scrollable
      ? [
          <span
            class={["el-tabs__nav-prev", scrollable.prev ? "" : "is-disabled"]}
            on-click={scrollPrev}
          >
            <i class="el-icon-arrow-left"></i>
          </span>,
          <span
            class={["el-tabs__nav-next", scrollable.next ? "" : "is-disabled"]}
            on-click={scrollNext}
          >
            <i class="el-icon-arrow-right"></i>
          </span>
        ]
      : null

    const tabs = this._l(panes, (pane, index) => {
      let tabName = pane.name || pane.index || index
      const closable = pane.isClosable || editable

      pane.index = `${index}`

      const btnClose = closable ? (
        <span
          class="el-icon-close"
          on-click={(ev) => {
            onTabRemove(pane, ev)
          }}
        ></span>
      ) : null

      const tabLabelContent = pane.$slots.label || pane.label
      const tabindex = pane.active ? 0 : -1
      return (
        <div
          class={{
            "el-tabs__item": true,
            [`is-${this.rootTabs.tabPosition}`]: true,
            "is-active": pane.active,
            "is-disabled": pane.disabled,
            "is-closable": closable,
            "is-focus": this.isFocus
          }}
          id={`tab-${tabName}`}
          key={`tab-${tabName}`}
          aria-controls={`pane-${tabName}`}
          role="tab"
          aria-selected={pane.active}
          ref="tabs"
          tabindex={tabindex}
          refInFor
          on-focus={() => {
            setFocus()
          }}
          on-blur={() => {
            removeFocus()
          }}
          on-dblclick={(ev) => {
            onTabEdit(pane, ev)
          }}
          on-click={(ev) => {
            removeFocus()
            onTabClick(pane, tabName, ev)
          }}
          on-keydown={(ev) => {
            if (closable && (ev.keyCode === 46 || ev.keyCode === 8)) {
              onTabRemove(pane, ev)
            }
          }}
        >
          {tabLabelContent}
          {btnClose}
        </div>
      )
    })
    return (
      <div
        class={[
          "el-tabs__nav-wrap",
          scrollable ? "is-scrollable" : "",
          `is-${this.rootTabs.tabPosition}`
        ]}
      >
        {scrollBtn}

        <div class={["el-tabs__nav-scroll"]} ref="navScroll">
          <div
            class={[
              "el-tabs__nav",
              `is-${this.rootTabs.tabPosition}`,
              stretch &&
              ["top", "bottom"].indexOf(this.rootTabs.tabPosition) !== -1
                ? "is-stretch"
                : ""
            ]}
            ref="nav"
            style={navStyle}
            role="tablist"
            on-keydown={changeTab}
          >
            {" "}
            <draggable value={tabListItem} onEnd={dragEnd}>
              {!type ? <tab-bar tabs={panes}></tab-bar> : null}
              {tabs}
            </draggable>
          </div>
        </div>
      </div>
    )
  },

  mounted() {
    addResizeListener(this.$el, this.update)
    document.addEventListener("visibilitychange", this.visibilityChangeHandler)
    window.addEventListener("blur", this.windowBlurHandler)
    window.addEventListener("focus", this.windowFocusHandler)
    setTimeout(() => {
      this.scrollToActiveTab()
    }, 0)
  },

  beforeDestroy() {
    if (this.$el && this.update) removeResizeListener(this.$el, this.update)
    document.removeEventListener(
      "visibilitychange",
      this.visibilityChangeHandler
    )
    window.removeEventListener("blur", this.windowBlurHandler)
    window.removeEventListener("focus", this.windowFocusHandler)
  }
}
</script>