tab-bar.js 11.9 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
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 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
import {
  TABBAR_HEIGHT
} from '../constants'

import {
  getRealPath,
  isTabBarPage
} from '../api/util'

import safeArea from './safe-area'

const IMAGE_TOP = 7
const IMAGE_WIDTH = 24
const IMAGE_HEIGHT = 24
const TEXT_TOP = 36
const TEXT_SIZE = 12
const TEXT_NOICON_SIZE = 17
const TEXT_HEIGHT = 12
const IMAGE_ID = 'TABITEM_IMAGE_'
const TABBAR_VIEW_ID = 'TABBAR_VIEW_'

let view
let config
let winWidth
let itemWidth
let itemLength
let itemImageLeft
let itemRects = []
const itemIcons = []
const itemLayouts = []
const itemDot = []
const itemBadge = []
let itemClickCallback

let selected = 0
/**
 * tabbar显示状态
 */
let visible = true

const init = function () {
  const list = config.list
  itemLength = config.list.length

  calcItemLayout(list) // 计算选项卡布局

  initBitmaps(list) // 初始化选项卡图标

  initView()
}

let initView = function () {
  const viewStyles = {
    height: TABBAR_HEIGHT
  }
  if (config.position === 'top') {
    viewStyles.top = 0
  } else {
    viewStyles.bottom = 0
    viewStyles.height += safeArea.bottom
  }
  view = new plus.nativeObj.View(TABBAR_VIEW_ID, viewStyles, getDraws())

  view.interceptTouchEvent(true)

  view.addEventListener('click', (e) => {
    if (!__uniConfig.__ready__) { // 未 ready,不允许点击
      return
    }
    const x = e.clientX
    const y = e.clientY
    for (let i = 0; i < itemRects.length; i++) {
      if (isCross(x, y, itemRects[i])) {
        const draws = getSelectedDraws(i)
        const drawTab = !!draws.length
        itemClickCallback && itemClickCallback(config.list[i], i, drawTab)
        if (drawTab) {
          setTimeout(() => view.draw(draws))
        }
        break
      }
    }
  })
  plus.globalEvent.addEventListener('orientationchange', () => {
    calcItemLayout(config.list)
    if (config.position !== 'top') {
      let height = TABBAR_HEIGHT + safeArea.bottom
      view.setStyle({
        height: height
      })
      if (visible) {
        setWebviewPosition(height)
      }
    }
    view.draw(getDraws())
  })
  if (!visible) {
    view.hide()
  }
}

let isCross = function (x, y, rect) {
  if (x > rect.left && x < (rect.left + rect.width) && y > rect.top && y < (rect.top + rect.height)) {
    return true
  }
  return false
}

let initBitmaps = function (list) {
  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    if (item.iconData) {
      const bitmap = new plus.nativeObj.Bitmap(IMAGE_ID + i)
      bitmap.loadBase64Data(item.iconData)
      const selectedBitmap = new plus.nativeObj.Bitmap(`${IMAGE_ID}SELECTED_${i}`)
      selectedBitmap.loadBase64Data(item.selectedIconData)
      itemIcons[i] = {
        icon: bitmap,
        selectedIcon: selectedBitmap
      }
    } else if (item.iconPath) {
      itemIcons[i] = {
        icon: item.iconPath,
        selectedIcon: item.selectedIconPath
      }
    } else {
      itemIcons[i] = {
        icon: false,
        selectedIcon: false
      }
    }
  }
}

let getDraws = function () {
  const backgroundColor = config.backgroundColor
  const borderHeight = Math.max(0.5, 1 / plus.screen.scale) // 高分屏最少0.5
  const borderTop = config.position === 'top' ? (TABBAR_HEIGHT - borderHeight) : 0
  const borderStyle = config.borderStyle === 'white' ? 'rgba(255,255,255,0.33)' : 'rgba(0,0,0,0.33)'

  const draws = [{
    id: `${TABBAR_VIEW_ID}BG`, // 背景色
    tag: 'rect',
    color: backgroundColor,
    position: {
      top: 0,
      left: 0,
      width: '100%',
      height: TABBAR_HEIGHT + safeArea.bottom
    }
  }, {
    id: `${TABBAR_VIEW_ID}BORDER`,
    tag: 'rect',
    color: borderStyle,
    position: {
      top: borderTop,
      left: 0,
      width: '100%',
      height: `${borderHeight}px`
    }
  }]

  for (let i = 0; i < itemLength; i++) {
    const item = config.list[i]
    if (i === selected) {
      drawTabItem(draws, i, item.text, config.selectedColor, itemIcons[i].selectedIcon)
    } else {
      drawTabItem(draws, i, item.text, config.color, itemIcons[i].icon)
    }
  }
  return draws
}

let getSelectedDraws = function (newSelected) {
  if (selected === newSelected) {
    return false
  }
  const draws = []
  const lastSelected = selected
  selected = newSelected
  drawTabItem(draws, lastSelected)
  drawTabItem(draws, selected)
  return draws
}
/**
 * 获取文字宽度(全角为1)
 * @param {*} text
 */
function getFontWidth (text) {
  // eslint-disable-next-line
  return text.length - (text.match(/[\u0000-\u00ff]/g) || []).length / 2
}
let calcItemLayout = function () {
  winWidth = plus.screen.resolutionWidth
  itemWidth = winWidth / itemLength
  itemImageLeft = (itemWidth - IMAGE_WIDTH) / 2
  itemRects = []
  let dotTop = 0
  let dotLeft = 0
  for (let i = 0; i < itemLength; i++) {
    itemRects.push({
      top: 0,
      left: i * itemWidth,
      width: itemWidth,
      height: TABBAR_HEIGHT
    })
  }

  for (let i = 0; i < itemLength; i++) {
    const item = config.list[i]
    let imgLeft = itemWidth * i + itemImageLeft
    if ((item.iconData || item.iconPath) && item.text) { // 图文
      itemLayouts[i] = {
        text: {
          top: TEXT_TOP,
          left: `${i * itemWidth}px`,
          width: `${itemWidth}px`,
          height: TEXT_HEIGHT
        },
        img: {
          top: IMAGE_TOP,
          left: `${imgLeft}px`,
          width: IMAGE_WIDTH,
          height: IMAGE_HEIGHT
        }
      }
      dotTop = IMAGE_TOP
      dotLeft = imgLeft + IMAGE_WIDTH
    } else if (!(item.iconData || item.iconPath) && item.text) { // 仅文字
      let textLeft = i * itemWidth
      itemLayouts[i] = {
        text: {
          top: 0,
          left: `${textLeft}px`,
          width: `${itemWidth}px`,
          height: TABBAR_HEIGHT
        }
      }
      dotTop = (44 - TEXT_NOICON_SIZE) / 2
      dotLeft = textLeft + itemWidth * 0.5 + getFontWidth(item.text) * TEXT_NOICON_SIZE * 0.5
    } else if ((item.iconData || item.iconPath) && !item.text) { // 仅图片
      const diff = 10
      let imgTop = (TABBAR_HEIGHT - IMAGE_HEIGHT - diff) / 2
      let imgLeft = itemWidth * i + itemImageLeft - diff / 2
      itemLayouts[i] = {
        img: {
          top: `${imgTop}px`,
          left: `${imgLeft}px`,
          width: IMAGE_WIDTH + diff,
          height: IMAGE_HEIGHT + diff
        }
      }
      dotTop = imgTop
      dotLeft = imgLeft + IMAGE_WIDTH + diff
    }
    let height = itemBadge[i] ? 14 : 10
    let badge = itemBadge[i] || '0'
    let font = getFontWidth(badge) - 0.5
    font = font > 1 ? 1 : font
    let width = height + font * 12
    width = width < height ? height : width
    let itemLayout = itemLayouts[i]
    if (itemLayout) {
      itemLayout.doc = {
        top: dotTop,
        left: `${dotLeft - width * 0.382}px`,
        width: `${width}px`,
        height: `${height}px`
      }
      itemLayout.badge = {
        top: dotTop,
        left: `${dotLeft - width * 0.382}px`,
        width: `${width}px`,
        height: `${height}px`
      }
    }
  }
}

let drawTabItem = function (draws, index) {
  const layout = itemLayouts[index]

  const item = config.list[index]

  let color = config.color
  let icon = itemIcons[index].icon
  let dot = itemDot[index]
  let badge = itemBadge[index] || ''

  if (index === selected) {
    color = config.selectedColor
    icon = itemIcons[index].selectedIcon
  }

  if (icon) {
    draws.push({
      id: `${TABBAR_VIEW_ID}ITEM_${index}_ICON`,
      tag: 'img',
      position: layout.img,
      src: icon
    })
  }
  if (item.text) {
    draws.push({
      id: `${TABBAR_VIEW_ID}ITEM_${index}_TEXT`,
      tag: 'font',
      position: layout.text,
      text: item.text,
      textStyles: {
        size: icon ? TEXT_SIZE : `${TEXT_NOICON_SIZE}px`,
        color
      }
    })
  }
  const hiddenPosition = {
    letf: 0,
    top: 0,
    width: 0,
    height: 0
  }
  // 绘制小红点(角标背景)
  draws.push({
    id: `${TABBAR_VIEW_ID}ITEM_${index}_DOT`,
    tag: 'rect',
    position: (dot || badge) ? layout.doc : hiddenPosition,
    rectStyles: {
      color: '#ff0000',
      radius: badge ? '7px' : '5px'
    }
  })
  // 绘制角标文本
  draws.push({
    id: `${TABBAR_VIEW_ID}ITEM_${index}_BADGE`,
    tag: 'font',
    position: badge ? layout.badge : hiddenPosition,
    text: badge || ' ',
    textStyles: {
      align: 'center',
      verticalAlign: 'middle',
      color: badge ? '#ffffff' : 'rgba(0,0,0,0)',
      overflow: 'ellipsis',
      size: '10px'
    }
  })
}
/**
 * {
    "color": "#7A7E83",
    "selectedColor": "#3cc51f",
    "borderStyle": "black",
    "backgroundColor": "#ffffff",
    "list": [{
      "pagePath": "page/component/index.html",
      "iconData": "",
      "selectedIconData": "",
      "text": "组件"
    }, {
      "pagePath": "page/API/index.html",
      "iconData": "",
      "selectedIconData": "",
      "text": "接口"
    }],
    "position":"bottom"//bottom|top
  }
 */

/**
 * 设置角标
 * @param {string} type
 * @param {number} index
 * @param {string} text
 */
function setTabBarBadge (type, index, text) {
  if (type === 'none') {
    itemDot[index] = false
    itemBadge[index] = ''
  } else if (type === 'text') {
    itemBadge[index] = text
  } else if (type === 'redDot') {
    itemDot[index] = true
  }
  if (view) {
    calcItemLayout(config.list)
    view.draw(getDraws())
  }
}
/**
 * 动态设置 tabBar 某一项的内容
 */
function setTabBarItem (index, text, iconPath, selectedIconPath) {
  if (iconPath || selectedIconPath) {
    let itemIcon = itemIcons[index] = itemIcons[index] || {}
    if (iconPath) {
      itemIcon.icon = getRealPath(iconPath)
    }
    if (selectedIconPath) {
      itemIcon.selectedIcon = getRealPath(selectedIconPath)
    }
  }
  if (text) {
    config.list[index].text = text
  }
  view.draw(getDraws())
}
/**
 * 动态设置 tabBar 的整体样式
 * @param {Object} style 样式
 */
function setTabBarStyle (style) {
  for (const key in style) {
    config[key] = style[key]
  }
  view.draw(getDraws())
}
/**
 * 设置tab页底部或顶部距离
 * @param {*} value 距离
 */
function setWebviewPosition (value) {
  const position = config.position === 'top' ? 'top' : 'bottom'
  plus.webview.all().forEach(webview => {
    if (isTabBarPage(String(webview.__uniapp_route))) {
      webview.setStyle({
        [position]: value
      })
    }
  })
}
/**
 * 隐藏 tabBar
 * @param {boolean} animation 是否需要动画效果 暂未支持
 */
function hideTabBar (animation) {
  if (visible === false) {
    return
  }
  visible = false
  if (view) {
    view.hide()
    setWebviewPosition(0)
  }
}
/**
 * 显示 tabBar
 * @param {boolean} animation 是否需要动画效果 暂未支持
 */
function showTabBar (animation) {
  if (visible === true) {
    return
  }
  visible = true
  if (view) {
    view.show()
    setWebviewPosition(TABBAR_HEIGHT + safeArea.bottom)
  }
}

export default {
  init (options, clickCallback) {
    if (options && options.list.length) {
      selected = options.selected || 0
      config = options
      config.position = 'bottom' // 暂时强制使用bottom
      itemClickCallback = clickCallback
      init()
      return view
    }
  },
  switchTab (page) {
    if (itemLength) {
      for (let i = 0; i < itemLength; i++) {
fxy060608's avatar
fxy060608 已提交
472 473 474 475
        if (
          config.list[i].pagePath === page ||
          config.list[i].pagePath === `${page}.html`
        ) {
fxy060608's avatar
fxy060608 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
          const draws = getSelectedDraws(i)
          if (draws.length) {
            view.draw(draws)
          }
          return true
        }
      }
    }
    return false
  },
  setTabBarBadge,
  setTabBarItem,
  setTabBarStyle,
  hideTabBar,
  showTabBar,
  get visible () {
    return visible
  }
}