uni-app-service.es.js 15.7 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
export function createServiceContext(Vue, weex, plus, UniServiceJSBridge,instanceContext){
const setTimeout = instanceContext.setTimeout;
const clearTimeout = instanceContext.clearTimeout;
const setInterval = instanceContext.setInterval;
const clearInterval = instanceContext.clearInterval;
const __uniConfig = instanceContext.__uniConfig;
const __uniRoutes = instanceContext.__uniRoutes;

var serviceContext = (function () {
    'use strict';

    /**
     * Make a map and return a function for checking if a key
     * is in that map.
     * IMPORTANT: all calls of this function must be prefixed with
     * \/\*#\_\_PURE\_\_\*\/
     * So that rollup can tree-shake them if necessary.
     */
    (process.env.NODE_ENV !== 'production')
        ? Object.freeze({})
        : {};
    (process.env.NODE_ENV !== 'production') ? Object.freeze([]) : [];
    const extend = Object.assign;
    const isString = (val) => typeof val === 'string';

    let isInitEntryPage = false;
    function initEntry() {
        if (isInitEntryPage) {
            return;
        }
        isInitEntryPage = true;
        let entryPagePath;
        let entryPageQuery;
        const weexPlus = weex.requireModule('plus');
        if (weexPlus.getRedirectInfo) {
            const info = weexPlus.getRedirectInfo() || {};
            entryPagePath = info.path;
            entryPageQuery = info.query ? '?' + info.query : '';
        }
        else {
            const argsJsonStr = plus.runtime.arguments;
            if (!argsJsonStr) {
                return;
            }
            try {
                const args = JSON.parse(argsJsonStr);
                entryPagePath = args.path || args.pathName;
                entryPageQuery = args.query ? '?' + args.query : '';
            }
            catch (e) { }
        }
        if (!entryPagePath || entryPagePath === __uniConfig.entryPagePath) {
            if (entryPageQuery) {
                __uniConfig.entryPageQuery = entryPageQuery;
            }
            return;
        }
        const entryRoute = '/' + entryPagePath;
        const routeOptions = __uniRoutes.find((route) => route.path === entryRoute);
        if (!routeOptions) {
            return;
        }
        if (!routeOptions.meta.isTabBar) {
            __uniConfig.realEntryPagePath =
                __uniConfig.realEntryPagePath || __uniConfig.entryPagePath;
        }
        __uniConfig.entryPagePath = entryPagePath;
        __uniConfig.entryPageQuery = entryPageQuery;
    }

    const cacheStringFunction = (fn) => {
        const cache = Object.create(null);
        return ((str) => {
            const hit = cache[str];
            return hit || (cache[str] = fn(str));
        });
    };
    const invokeArrayFns = (fns, arg) => {
        let ret;
        for (let i = 0; i < fns.length; i++) {
            ret = fns[i](arg);
        }
        return ret;
    };
    const TABBAR_HEIGHT = 50;
    const SCHEME_RE = /^([a-z-]+:)?\/\//i;
    const DATA_RE = /^data:.*,.*/;
    const WEB_INVOKE_APPSERVICE = 'WEB_INVOKE_APPSERVICE';

    function getRealRoute(fromRoute, toRoute) {
        if (toRoute.indexOf('/') === 0) {
            return toRoute;
        }
        if (toRoute.indexOf('./') === 0) {
            return getRealRoute(fromRoute, toRoute.substr(2));
        }
        const toRouteArray = toRoute.split('/');
        const toRouteLength = toRouteArray.length;
        let i = 0;
        for (; i < toRouteLength && toRouteArray[i] === '..'; i++) {
            // noop
        }
        toRouteArray.splice(0, i);
        toRoute = toRouteArray.join('/');
        const fromRouteArray = fromRoute.length > 0 ? fromRoute.split('/') : [];
        fromRouteArray.splice(fromRouteArray.length - i - 1, i + 1);
        return '/' + fromRouteArray.concat(toRouteArray).join('/');
    }

    function getCurrentPage() {
        const pages = getCurrentPages();
        const len = pages.length;
        if (len) {
            return pages[len - 1];
        }
    }
    function getCurrentPageVm() {
        const page = getCurrentPage();
        if (page) {
            return page.$vm;
        }
    }
    function invokeHook(vm, name, args) {
        if (isString(vm)) {
            args = name;
            name = vm;
            vm = getCurrentPageVm();
        }
        else if (typeof vm === 'number') {
            const page = getCurrentPages().find((page) => page.$page.id === vm);
            if (page) {
                vm = page.$vm;
            }
            else {
                vm = getCurrentPageVm();
            }
        }
        if (!vm) {
            return;
        }
        const hooks = vm.$[name];
        return hooks && invokeArrayFns(hooks, args);
    }

    function getRealPath(filepath) {
        // 无协议的情况补全 https
        if (filepath.indexOf('//') === 0) {
            return 'https:' + filepath;
        }
        // 网络资源或base64
        if (SCHEME_RE.test(filepath) || DATA_RE.test(filepath)) {
            return filepath;
        }
        if (isSystemURL(filepath)) {
            return 'file://' + normalizeLocalPath(filepath);
        }
        const wwwPath = 'file://' + normalizeLocalPath('_www');
        // 绝对路径转换为本地文件系统路径
        if (filepath.indexOf('/') === 0) {
            // 平台绝对路径 安卓、iOS
            if (filepath.startsWith('/storage/') ||
                filepath.includes('/Containers/Data/Application/')) {
                return 'file://' + filepath;
            }
            return wwwPath + filepath;
        }
        // 相对资源
        if (filepath.indexOf('../') === 0 || filepath.indexOf('./') === 0) {
            // @ts-expect-error app-view
            if (typeof __id__ === 'string') {
                // @ts-expect-error app-view
                return wwwPath + getRealRoute('/' + __id__, filepath);
            }
            else {
                const pages = getCurrentPages();
                if (pages.length) {
                    return (wwwPath + getRealRoute('/' + pages[pages.length - 1].route, filepath));
                }
            }
        }
        return filepath;
    }
    const normalizeLocalPath = cacheStringFunction((filepath) => {
        return plus.io
            .convertLocalFileSystemURL(filepath)
            .replace(/^\/?apps\//, '/android_asset/apps/')
            .replace(/\/$/, '');
    });
    function isSystemURL(filepath) {
        if (filepath.indexOf('_www') === 0 ||
            filepath.indexOf('_doc') === 0 ||
            filepath.indexOf('_documents') === 0 ||
            filepath.indexOf('_downloads') === 0) {
            return true;
        }
        return false;
    }

    const isIOS = plus.os.name === 'iOS';
    let config;
    /**
     * tabbar显示状态
     */
    let visible = true;
    let tabBar;
    /**
     * 设置角标
     * @param {string} type
     * @param {number} index
     * @param {string} text
     */
    function setTabBarBadge(type, index, text) {
        if (!tabBar) {
            return;
        }
        if (type === 'none') {
            tabBar.hideTabBarRedDot({
                index,
            });
            tabBar.removeTabBarBadge({
                index,
            });
        }
        else if (type === 'text') {
            tabBar.setTabBarBadge({
                index,
                text,
            });
        }
        else if (type === 'redDot') {
            tabBar.showTabBarRedDot({
                index,
            });
        }
    }
    /**
     * 动态设置 tabBar 某一项的内容
     */
    function setTabBarItem(index, text, iconPath, selectedIconPath) {
        const item = {
            index,
        };
        if (text !== undefined) {
            item.text = text;
        }
        if (iconPath) {
            item.iconPath = getRealPath(iconPath);
        }
        if (selectedIconPath) {
            item.selectedIconPath = getRealPath(selectedIconPath);
        }
        tabBar && tabBar.setTabBarItem(item);
    }
    /**
     * 动态设置 tabBar 的整体样式
     * @param {Object} style 样式
     */
    function setTabBarStyle(style) {
        tabBar && tabBar.setTabBarStyle(style);
    }
    /**
     * 隐藏 tabBar
     * @param {boolean} animation 是否需要动画效果
     */
    function hideTabBar(animation) {
        visible = false;
        tabBar &&
            tabBar.hideTabBar({
                animation,
            });
    }
    /**
     * 显示 tabBar
     * @param {boolean} animation 是否需要动画效果
     */
    function showTabBar(animation) {
        visible = true;
        tabBar &&
            tabBar.showTabBar({
                animation,
            });
    }
    const maskClickCallback = [];
fxy060608's avatar
fxy060608 已提交
284
    var tabBarInstance = {
fxy060608's avatar
fxy060608 已提交
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
        id: '0',
        init(options, clickCallback) {
            if (options && options.list.length) {
                config = options;
            }
            try {
                tabBar = weex.requireModule('uni-tabview');
            }
            catch (error) {
                console.log(`uni.requireNativePlugin("uni-tabview") error ${error}`);
            }
            tabBar.onMaskClick(() => {
                maskClickCallback.forEach((callback) => {
                    callback();
                });
            });
            tabBar &&
                tabBar.onClick(({ index }) => {
                    clickCallback(config.list[index], index);
                });
            tabBar &&
                tabBar.onMidButtonClick(() => {
                    // publish('onTabBarMidButtonTap', {})
                });
        },
        indexOf(page) {
            const itemLength = config && config.list && config.list.length;
            if (itemLength) {
                for (let i = 0; i < itemLength; i++) {
                    if (config.list[i].pagePath === page ||
                        config.list[i].pagePath === `${page}.html`) {
                        return i;
                    }
                }
            }
            return -1;
        },
        switchTab(page) {
            const index = this.indexOf(page);
            if (index >= 0) {
                tabBar &&
                    tabBar.switchSelect({
                        index,
                    });
                return true;
            }
            return false;
        },
        setTabBarBadge,
        setTabBarItem,
        setTabBarStyle,
        hideTabBar,
        showTabBar,
        append(webview) {
            tabBar &&
                tabBar.append({
                    id: webview.id,
                }, ({ code }) => {
                    if (code !== 0) {
                        setTimeout(() => {
                            this.append(webview);
                        }, 20);
                    }
                });
        },
        get visible() {
            return visible;
        },
        get height() {
            return ((config && config.height ? parseFloat(config.height) : TABBAR_HEIGHT) +
                plus.navigator.getSafeAreaInsets().deviceBottom);
        },
        // tabBar是否遮挡内容区域
        get cover() {
            const array = ['extralight', 'light', 'dark'];
            return isIOS && array.indexOf(config.blurEffect) >= 0;
        },
        setStyle({ mask }) {
            tabBar.setMask({
                color: mask,
            });
        },
        addEventListener(_name, callback) {
            maskClickCallback.push(callback);
        },
        removeEventListener(_name, callback) {
            const callbackIndex = maskClickCallback.indexOf(callback);
            maskClickCallback.splice(callbackIndex, 1);
        },
    };

    function initTabBar() {
fxy060608's avatar
fxy060608 已提交
377 378
        const { tabBar } = __uniConfig;
        const len = tabBar && tabBar.list && tabBar.list.length;
fxy060608's avatar
fxy060608 已提交
379 380 381
        if (!len) {
            return;
        }
fxy060608's avatar
fxy060608 已提交
382 383 384 385
        const { entryPagePath } = __uniConfig;
        tabBar.selectedIndex = 0;
        const selected = tabBar.list.findIndex((page) => page.pagePath === entryPagePath);
        tabBarInstance.init(tabBar, (item, index) => {
fxy060608's avatar
fxy060608 已提交
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
            uni.switchTab({
                url: '/' + item.pagePath,
                openType: 'switchTab',
                from: 'tabBar',
                success() {
                    invokeHook('onTabItemTap', {
                        index,
                        text: item.text,
                        pagePath: item.pagePath,
                    });
                },
            });
        });
        if (selected !== -1) {
            // 取当前 tab 索引值
fxy060608's avatar
fxy060608 已提交
401 402
            tabBar.selectedIndex = selected;
            selected !== 0 && tabBarInstance.switchTab(entryPagePath);
fxy060608's avatar
fxy060608 已提交
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 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
        }
    }

    const callbacks = {};
    // 简单处理 view 层与 service 层的通知系统
    /**
     * 消费 view 层通知
     */
    function consumePlusMessage(type, args) {
        // 处理 web-view 组件发送的通知
        if (type === WEB_INVOKE_APPSERVICE) {
            UniServiceJSBridge.emit('onWebInvokeAppService', args.data, args.webviewIds);
            return true;
        }
        const callback = callbacks[type];
        if (callback) {
            callback(args);
            if (!callback.keepAlive) {
                delete callbacks[type];
            }
            return true;
        }
        return false;
    }

    function backbuttonListener() {
        uni.navigateBack({
            from: 'backbutton',
        });
    }

    function initGlobalEvent() {
        const plusGlobalEvent = plus.weexGlobalEvent;
        const weexGlobalEvent = weex.requireModule('weexGlobalEvent');
        const emit = UniServiceJSBridge.emit;
        if (weex.config.preload) {
            plus.key.addEventListener('backbutton', backbuttonListener);
        }
        else {
            plusGlobalEvent.addEventListener('splashclosed', () => {
                plus.key.addEventListener('backbutton', backbuttonListener);
            });
        }
        plusGlobalEvent.addEventListener('pause', () => {
            emit('onAppEnterBackground');
        });
        plusGlobalEvent.addEventListener('resume', () => {
            emit('onAppEnterForeground');
        });
        weexGlobalEvent.addEventListener('uistylechange', function (event) {
            const args = {
                theme: event.uistyle,
            };
            emit('onThemeChange', args);
        });
        plusGlobalEvent.addEventListener('plusMessage', onPlusMessage);
        // nvue webview post message
        plusGlobalEvent.addEventListener('WebviewPostMessage', onPlusMessage);
    }
    function onPlusMessage(e) {
        if (e.data && e.data.type) {
            const type = e.data.type;
            consumePlusMessage(type, e.data.args || {});
        }
    }

    let appCtx;
    const defaultApp = {
        globalData: {},
    };
    function registerApp(appVm) {
        appCtx = appVm;
        appCtx.$vm = appVm;
        extend(appCtx, defaultApp); // 拷贝默认实现
        const { $options } = appVm;
        if ($options) {
            appCtx.globalData = extend($options.globalData || {}, appCtx.globalData);
        }
        initEntry();
        initTabBar();
        initGlobalEvent();
    }

    var index = {
        __registerApp: registerApp,
    };

    return index;

}());
const uni = serviceContext.uni;
const getApp = serviceContext.getApp;
const getCurrentPages = serviceContext.getCurrentPages;
const __definePage = serviceContext.__definePage;
const __registerPage = serviceContext.__registerPage;
return serviceContext;
}