index.legacy.js 17.8 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10
const hasOwnProperty = Object.prototype.hasOwnProperty;

function isFn (fn) {
  return typeof fn === 'function'
}

function hasOwn (obj, key) {
  return hasOwnProperty.call(obj, key)
}

fxy060608's avatar
fxy060608 已提交
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
const globalInterceptors = {};
const scopedInterceptors = {};

function wrapperHook (hook) {
  return function (data) {
    return hook(data) || data
  }
}

function isPromise (obj) {
  return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}

function queue (hooks, data) {
  let promise = false;
  for (let i = 0; i < hooks.length; i++) {
    const hook = hooks[i];
    if (promise) {
      promise = Promise.then(wrapperHook(hook));
    } else {
      const res = hook(data);
      if (isPromise(res)) {
        promise = Promise.resolve(res);
      }
      if (res === false) {
        return {
          then () {}
        }
      }
    }
  }
  return promise || {
    then (callback) {
      return callback(data)
    }
  }
}

function wrapperOptions (interceptor, options = {}) {
  ['success', 'fail', 'complete'].forEach(name => {
    if (Array.isArray(interceptor[name])) {
      const oldCallback = options[name];
      options[name] = function callbackInterceptor (res) {
        queue(interceptor[name], res).then((res) => {
          /* eslint-disable no-mixed-operators */
          return isFn(oldCallback) && oldCallback(res) || res
        });
      };
    }
  });
  return options
}

function wrapperReturnValue (method, returnValue) {
  const returnValueHooks = [];
  if (Array.isArray(globalInterceptors.returnValue)) {
    returnValueHooks.push(...globalInterceptors.returnValue);
  }
  const interceptor = scopedInterceptors[method];
  if (interceptor && Array.isArray(interceptor.returnValue)) {
    returnValueHooks.push(...interceptor.returnValue);
  }
  returnValueHooks.forEach(hook => {
    returnValue = hook(returnValue) || returnValue;
  });
  return returnValue
}

function getApiInterceptorHooks (method) {
  const interceptor = Object.create(null);
  Object.keys(globalInterceptors).forEach(hook => {
    if (hook !== 'returnValue') {
      interceptor[hook] = globalInterceptors[hook].slice();
    }
  });
  const scopedInterceptor = scopedInterceptors[method];
  if (scopedInterceptor) {
    Object.keys(scopedInterceptor).forEach(hook => {
      if (hook !== 'returnValue') {
        interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
      }
    });
  }
  return interceptor
}

function invokeApi (method, api, options, ...params) {
  const interceptor = getApiInterceptorHooks(method);
  if (interceptor && Object.keys(interceptor).length) {
    if (Array.isArray(interceptor.invoke)) {
      const res = queue(interceptor.invoke, options);
      return res.then((options) => {
        return api(wrapperOptions(interceptor, options), ...params)
      })
    } else {
      return api(wrapperOptions(interceptor, options), ...params)
    }
  }
  return api(options, ...params)
}

const SYNC_API_RE =
    /^\$|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/;
fxy060608's avatar
fxy060608 已提交
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

const CONTEXT_API_RE = /^create|Manager$/;

const CALLBACK_API_RE = /^on/;

function isContextApi (name) {
  return CONTEXT_API_RE.test(name)
}
function isSyncApi (name) {
  return SYNC_API_RE.test(name)
}

function isCallbackApi (name) {
  return CALLBACK_API_RE.test(name)
}

function handlePromise (promise) {
  return promise.then(data => {
    return [null, data]
  })
    .catch(err => [err])
}

function shouldPromise (name) {
  if (
    isContextApi(name) ||
        isSyncApi(name) ||
        isCallbackApi(name)
  ) {
    return false
  }
  return true
}

function promisify (name, api) {
  if (!shouldPromise(name)) {
    return api
  }
  return function promiseApi (options = {}, ...params) {
    if (isFn(options.success) || isFn(options.fail) || isFn(options.complete)) {
fxy060608's avatar
fxy060608 已提交
154
      return wrapperReturnValue(name, invokeApi(name, api, options, ...params))
fxy060608's avatar
fxy060608 已提交
155
    }
fxy060608's avatar
fxy060608 已提交
156 157
    return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
      invokeApi(name, api, Object.assign({}, options, {
fxy060608's avatar
fxy060608 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
        success: resolve,
        fail: reject
      }), ...params);
      /* eslint-disable no-extend-native */
      if (!Promise.prototype.finally) {
        Promise.prototype.finally = function (callback) {
          const promise = this.constructor;
          return this.then(
            value => promise.resolve(callback()).then(() => value),
            reason => promise.resolve(callback()).then(() => {
              throw reason
            })
          )
        };
      }
fxy060608's avatar
fxy060608 已提交
173
    })))
fxy060608's avatar
fxy060608 已提交
174 175 176 177 178 179 180
  }
}

const SUCCESS = 'success';
const FAIL = 'fail';
const COMPLETE = 'complete';
const CALLBACKS = [SUCCESS, FAIL, COMPLETE];
181 182 183

const UNIAPP_SERVICE_NVUE_ID = '__uniapp__service';

fxy060608's avatar
fxy060608 已提交
184
function noop () {
185 186

}
fxy060608's avatar
fxy060608 已提交
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
/**
 * 调用无参数,或仅一个参数且为 callback 的 API
 * @param {Object} vm
 * @param {Object} method
 * @param {Object} args
 * @param {Object} extras
 */
function invokeVmMethodWithoutArgs (vm, method, args, extras) {
  if (!vm) {
    return
  }
  if (typeof args === 'undefined') {
    return vm[method]()
  }
  const [, callbacks] = normalizeArgs(args, extras);
  if (!Object.keys(callbacks).length) {
    return vm[method]()
  }
  return vm[method](normalizeCallback(method, callbacks))
}
/**
 * 调用两个参数(第一个入参为普通参数,第二个入参为 callback) API
 * @param {Object} vm
 * @param {Object} method
 * @param {Object} args
 * @param {Object} extras
 */
function invokeVmMethod (vm, method, args, extras) {
  if (!vm) {
    return
  }
  const [pureArgs, callbacks] = normalizeArgs(args, extras);
  if (!Object.keys(callbacks).length) {
    return vm[method](pureArgs)
  }
  return vm[method](pureArgs, normalizeCallback(method, callbacks))
}

function findRefById (id, vm) {
  return findRefByVNode(id, vm._vnode)
}

function findRefByVNode (id, vnode) {
  if (!id || !vnode) {
    return
  }
  if (vnode.data &&
        vnode.data.ref &&
        vnode.data.attrs &&
        vnode.data.attrs.id === id) {
    return vnode.data.ref
  }
  const children = vnode.children;
  if (!children) {
    return
  }
  for (let i = 0, len = children.length; i < len; i++) {
    const ref = findRefByVNode(id, children[i]);
    if (ref) {
      return ref
    }
  }
}

function normalizeArgs (args = {}, extras) {
  const callbacks = Object.create(null);

  const iterator = function iterator (name) {
    const callback = args[name];
    if (isFn(callback)) {
      callbacks[name] = callback;
      delete args[name];
    }
  };

  CALLBACKS.forEach(iterator);

  extras && extras.forEach(iterator);

  return [args, callbacks]
}

function normalizeCallback (method, callbacks) {
  return function weexCallback (ret) {
    const type = ret.type;
    delete ret.type;
    const callback = callbacks[type];

    if (type === SUCCESS) {
      ret.errMsg = `${method}:ok`;
    } else if (type === FAIL) {
      ret.errMsg = method + ':fail' + (ret.msg ? (' ' + ret.msg) : '');
    }

    delete ret.code;
    delete ret.msg;

    isFn(callback) && callback(ret);

    if (type === SUCCESS || type === FAIL) {
      const complete = callbacks['complete'];
      isFn(complete) && complete(ret);
    }
  }
}

293 294 295 296
function initSubNVue (nvue, plus, BroadcastChannel) {
  let origin;

  const onMessageCallbacks = [];
fxy060608's avatar
fxy060608 已提交
297 298

  const postMessage = nvue.requireModule('plus').postMessage;
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

  const onSubNVueMessage = function onSubNVueMessage (data) {
    onMessageCallbacks.forEach(callback => callback({
      origin,
      data
    }));
  };

  nvue.requireModule('globalEvent').addEventListener('plusMessage', e => {
    if (e.data.type === 'UniAppSubNVue') {
      onSubNVueMessage(e.data.data, e.data.options);
    }
  });

  const webviewId = plus.webview.currentWebview().id;

  const channel = new BroadcastChannel('UNI-APP-SUBNVUE');
  channel.onmessage = function (event) {
    if (event.data.to === webviewId) {
      onSubNVueMessage(event.data.data);
    }
  };

  const wrapper = function wrapper (webview) {
    webview.$processed = true;

    const currentWebviewId = plus.webview.currentWebview().id;
    const isPopupNVue = currentWebviewId === webview.id;

    const hostNVueId = webview.__uniapp_origin_type === 'uniNView' && webview.__uniapp_origin_id;
    const popupNVueId = webview.id;

    webview.postMessage = function (data) {
      if (hostNVueId) {
        channel.postMessage({
          data,
          to: isPopupNVue ? hostNVueId : popupNVueId
        });
      } else {
fxy060608's avatar
fxy060608 已提交
338
        postMessage({
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
          type: 'UniAppSubNVue',
          data: data
        }, UNIAPP_SERVICE_NVUE_ID);
      }
    };
    webview.onMessage = function (callback) {
      onMessageCallbacks.push(callback);
    };

    if (!webview.__uniapp_mask_id) {
      return
    }
    origin = webview.__uniapp_host;

    const maskColor = webview.__uniapp_mask;

    let maskWebview = plus.webview.getWebviewById(webview.__uniapp_mask_id);
    maskWebview = maskWebview.parent() || maskWebview; // 再次检测父
    const oldShow = webview.show;
    const oldHide = webview.hide;
    const oldClose = webview.close;

    const showMask = function () {
      maskWebview.setStyle({
        mask: maskColor
      });
    };
    const closeMask = function () {
      maskWebview.setStyle({
        mask: 'none'
      });
    };
    webview.show = function (...args) {
      showMask();
      return oldShow.apply(webview, args)
    };
    webview.hide = function (...args) {
      closeMask();
      return oldHide.apply(webview, args)
    };
    webview.close = function (...args) {
      closeMask();
      return oldClose.apply(webview, args)
    };
  };

  const getSubNVueById = function getSubNVueById (id) {
    const webview = plus.webview.getWebviewById(id);
    if (webview && !webview.$processed) {
      wrapper(webview);
    }
    return webview
  };

  return {
    getSubNVueById,
    getCurrentSubNVue () {
      return getSubNVueById(plus.webview.currentWebview().id)
    }
  }
}

fxy060608's avatar
fxy060608 已提交
401 402
function initPostMessage (nvue) {
  const plus = nvue.requireModule('plus');
403 404 405 406 407 408 409 410 411
  return {
    postMessage (data) {
      plus.postMessage(data, UNIAPP_SERVICE_NVUE_ID);
    }
  }
}

function initTitleNView (nvue) {
  const eventMaps = {
fxy060608's avatar
fxy060608 已提交
412 413 414 415
    onNavigationBarButtonTap: noop,
    onNavigationBarSearchInputChanged: noop,
    onNavigationBarSearchInputConfirmed: noop,
    onNavigationBarSearchInputClicked: noop
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 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
  };
  nvue.requireModule('globalEvent').addEventListener('plusMessage', e => {
    if (eventMaps[e.data.type]) {
      eventMaps[e.data.type](e.data.data);
    }
  });
  const ret = Object.create(null);
  Object.keys(eventMaps).forEach(eventType => {
    ret[eventType] = function (callback) {
      eventMaps[eventType] = callback;
    };
  });
  return ret
}

const EPS = 1e-4;
const BASE_DEVICE_WIDTH = 750;
let isIOS = false;
let deviceWidth = 0;
let deviceDPR = 0;

function upx2px (number, newDeviceWidth) {
  number = Number(number);
  if (number === 0) {
    return 0
  }
  let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth);
  if (result < 0) {
    result = -result;
  }
  result = Math.floor(result + EPS);
  if (result === 0) {
    if (deviceDPR === 1 || !isIOS) {
      return 1
    } else {
      return 0.5
    }
  }
  return number < 0 ? -result : result
}

function initUpx2px (nvue) {
  const env = nvue.config.env;

  deviceDPR = env.scale;
  deviceWidth = Math.ceil(env.deviceWidth / deviceDPR);
  isIOS = env.platform === 'iOS';
}

let getEmitter;

function apply (ctx, method, args) {
  return ctx[method].apply(ctx, args)
}

function $on () {
  return apply(getEmitter(), '$on', [...arguments])
}
function $off () {
  return apply(getEmitter(), '$off', [...arguments])
}
function $once () {
  return apply(getEmitter(), '$once', [...arguments])
}
function $emit () {
  return apply(getEmitter(), '$emit', [...arguments])
}

function initEventBus (getGlobalEmitter) {
  getEmitter = getGlobalEmitter;
}

fxy060608's avatar
fxy060608 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
class MapContext {
  constructor (id, ctx) {
    this.id = id;
    this.ctx = ctx;
  }

  getCenterLocation (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'getCenterLocation', cbs)
  }

  moveToLocation () {
    return invokeVmMethodWithoutArgs(this.ctx, 'moveToLocation')
  }

  translateMarker (args) {
    return invokeVmMethod(this.ctx, 'translateMarker', args, ['animationEnd'])
  }

  includePoints (args) {
    return invokeVmMethod(this.ctx, 'includePoints', args)
  }

  getRegion (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'getRegion', cbs)
  }

  getScale (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'getScale', cbs)
  }
}

function createMapContext (id, vm) {
  const ref = findRefById(id, vm);
  if (!ref) {
    global.nativeLog('Can not find `' + id + '`', '__WARN');
  }
  return new MapContext(id, vm.$refs[ref])
}

527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
class VideoContext {
  constructor (id, ctx) {
    this.id = id;
    this.ctx = ctx;
  }

  play () {
    return invokeVmMethodWithoutArgs(this.ctx, 'play')
  }

  pause () {
    return invokeVmMethodWithoutArgs(this.ctx, 'pause')
  }

  seek (args) {
    return invokeVmMethod(this.ctx, 'seek', args)
  }

  stop () {
    return invokeVmMethodWithoutArgs(this.ctx, 'stop')
  }

  sendDanmu (args) {
    return invokeVmMethod(this.ctx, 'sendDanmu', args)
  }

  playbackRate (args) {
    return invokeVmMethod(this.ctx, 'playbackRate', args)
  }

  requestFullScreen (args) {
    return invokeVmMethod(this.ctx, 'requestFullScreen', args)
  }

  exitFullScreen () {
    return invokeVmMethodWithoutArgs(this.ctx, 'exitFullScreen')
  }

  showStatusBar () {
    return invokeVmMethodWithoutArgs(this.ctx, 'showStatusBar')
  }

  hideStatusBar () {
    return invokeVmMethodWithoutArgs(this.ctx, 'hideStatusBar')
  }
}

function createVideoContext (id, vm) {
  const ref = findRefById(id, vm);
  if (!ref) {
    global.nativeLog('Can not find `' + id + '`', '__WARN');
  }
  return new VideoContext(id, vm.$refs[ref])
}

class LivePusherContext {
  constructor (id, ctx) {
    this.id = id;
    this.ctx = ctx;
  }

  start (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'start', cbs)
  }

  stop (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'stop', cbs)
  }

  pause (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'pause', cbs)
  }

  resume (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'resume', cbs)
  }

  switchCamera (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'switchCamera', cbs)
  }

  snapshot (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'snapshot', cbs)
  }

  toggleTorch (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'toggleTorch', cbs)
  }

  playBGM (args) {
    return invokeVmMethod(this.ctx, 'playBGM', args)
  }

  stopBGM (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'stopBGM', cbs)
  }

  pauseBGM (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'pauseBGM', cbs)
  }

  resumeBGM (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'resumeBGM', cbs)
  }

  setBGMVolume (cbs) {
    return invokeVmMethod(this.ctx, 'setBGMVolume', cbs)
  }

  startPreview (cbs) {
    return invokeVmMethodWithoutArgs(this.ctx, 'startPreview', cbs)
  }

  stopPreview (args) {
    return invokeVmMethodWithoutArgs(this.ctx, 'stopPreview', args)
  }
}

function createLivePusherContext (id, vm) {
  const ref = findRefById(id, vm);
  if (!ref) {
    global.nativeLog('Can not find `' + id + '`', '__WARN');
  }
  return new LivePusherContext(id, vm.$refs[ref])
}

fxy060608's avatar
fxy060608 已提交
653 654 655 656 657 658 659 660


var apis = /*#__PURE__*/Object.freeze({
  upx2px: upx2px,
  $on: $on,
  $once: $once,
  $off: $off,
  $emit: $emit,
661 662 663
  createMapContext: createMapContext,
  createVideoContext: createVideoContext,
  createLivePusherContext: createLivePusherContext
fxy060608's avatar
fxy060608 已提交
664 665
});

666 667 668 669 670 671 672 673 674 675
function initUni (uni, nvue, plus, BroadcastChannel) {
  const {
    getSubNVueById,
    getCurrentSubNVue
  } = initSubNVue(nvue, plus, BroadcastChannel);

  const scopedApis = Object.assign({
    getSubNVueById,
    getCurrentSubNVue,
    requireNativePlugin: nvue.requireModule
fxy060608's avatar
fxy060608 已提交
676
  }, initTitleNView(nvue), initPostMessage(nvue));
677

fxy060608's avatar
fxy060608 已提交
678 679 680 681 682 683
  if (typeof Proxy !== 'undefined') {
    return new Proxy({}, {
      get (target, name) {
        if (apis[name]) {
          return apis[name]
        }
684 685
        if (scopedApis[name]) {
          return scopedApis[name]
fxy060608's avatar
fxy060608 已提交
686 687 688 689 690 691 692 693 694 695 696 697 698 699
        }
        if (!hasOwn(uni, name)) {
          return
        }
        return promisify(name, uni[name])
      }
    })
  }
  const ret = {
    requireNativePlugin: nvue.requireModule
  };
  Object.keys(apis).forEach(name => {
    ret[name] = apis[name];
  });
700 701 702
  Object.keys(scopedApis).forEach(name => {
    ret[name] = scopedApis[name];
  });
fxy060608's avatar
fxy060608 已提交
703 704 705 706 707 708 709 710 711 712 713
  Object.keys(uni).forEach(name => {
    ret[name] = promisify(name, uni[name]);
  });
  return ret
}

let getGlobalUni;
let getGlobalApp;
let getGlobalUniEmitter;
let getGlobalCurrentPages;

fxy060608's avatar
fxy060608 已提交
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
function createInstanceContext () {
  return {
    initUniApp ({
      nvue,
      getUni,
      getApp,
      getUniEmitter,
      getCurrentPages
    }) {
      getGlobalUni = getUni;
      getGlobalApp = getApp;
      getGlobalUniEmitter = getUniEmitter;
      getGlobalCurrentPages = getCurrentPages;

      initUpx2px(nvue);
      initEventBus(getUniEmitter);
    },
    getUni (nvue, plus, BroadcastChannel) {
      return initUni(getGlobalUni(), nvue, plus, BroadcastChannel)
    },
    getApp () {
      return getGlobalApp()
    },
    getUniEmitter () {
      return getGlobalUniEmitter()
    },
    getCurrentPages () {
      return getGlobalCurrentPages()
fxy060608's avatar
fxy060608 已提交
742 743
    }
  }
fxy060608's avatar
fxy060608 已提交
744
}
fxy060608's avatar
fxy060608 已提交
745

fxy060608's avatar
fxy060608 已提交
746
export { createInstanceContext };