uni-shared.es.js 37.7 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import { isHTMLTag, isSVGTag, hyphenate, camelize, extend, isString, isPlainObject, isArray, toTypeString, toRawType, capitalize } from '@vue/shared';
fxy060608's avatar
fxy060608 已提交
2

3
const BUILT_IN_TAG_NAMES = [
fxy060608's avatar
fxy060608 已提交
4
    'ad',
fxy060608's avatar
fxy060608 已提交
5 6
    'ad-content-page',
    'ad-draw',
fxy060608's avatar
fxy060608 已提交
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
    'audio',
    'button',
    'camera',
    'canvas',
    'checkbox',
    'checkbox-group',
    'cover-image',
    'cover-view',
    'editor',
    'form',
    'functional-page-navigator',
    'icon',
    'image',
    'input',
    'label',
    'live-player',
    'live-pusher',
    'map',
    'movable-area',
    'movable-view',
    'navigator',
    'official-account',
    'open-data',
    'picker',
    'picker-view',
    'picker-view-column',
    'progress',
    'radio',
    'radio-group',
    'rich-text',
    'scroll-view',
    'slider',
    'swiper',
    'swiper-item',
    'switch',
    'text',
    'textarea',
    'video',
    'view',
    'web-view',
47 48
];
const BUILT_IN_TAGS = BUILT_IN_TAG_NAMES.map((tag) => 'uni-' + tag);
fxy060608's avatar
fxy060608 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
const TAGS = [
    'app',
    'layout',
    'content',
    'main',
    'top-window',
    'left-window',
    'right-window',
    'tabbar',
    'page',
    'page-head',
    'page-wrapper',
    'page-body',
    'page-refresh',
    'actionsheet',
    'modal',
    'toast',
    'resize-sensor',
    'shadow-root',
].map((tag) => 'uni-' + tag);
function isBuiltInComponent(tag) {
70 71
    // h5 平台会被转换为 v-uni-
    return BUILT_IN_TAGS.indexOf('uni-' + tag.replace('v-uni-', '')) !== -1;
fxy060608's avatar
fxy060608 已提交
72
}
fxy060608's avatar
fxy060608 已提交
73
function isH5CustomElement(tag) {
fxy060608's avatar
fxy060608 已提交
74 75
    return TAGS.indexOf(tag) !== -1 || BUILT_IN_TAGS.indexOf(tag) !== -1;
}
fxy060608's avatar
fxy060608 已提交
76
function isH5NativeTag(tag) {
fxy060608's avatar
fxy060608 已提交
77 78 79
    return (tag !== 'head' &&
        (isHTMLTag(tag) || isSVGTag(tag)) &&
        !isBuiltInComponent(tag));
fxy060608's avatar
fxy060608 已提交
80
}
fxy060608's avatar
fxy060608 已提交
81
function isAppNativeTag(tag) {
fxy060608's avatar
fxy060608 已提交
82 83
    return isHTMLTag(tag) || isSVGTag(tag) || isBuiltInComponent(tag);
}
fxy060608's avatar
fxy060608 已提交
84 85 86 87 88 89 90
function isMiniProgramNativeTag(tag) {
    return isBuiltInComponent(tag);
}
function createIsCustomElement(tags = []) {
    return function isCustomElement(tag) {
        return tags.includes(tag);
    };
fxy060608's avatar
fxy060608 已提交
91
}
fxy060608's avatar
fxy060608 已提交
92 93 94
function isComponentTag(tag) {
    return tag[0].toLowerCase() + tag.slice(1) === 'component';
}
fxy060608's avatar
fxy060608 已提交
95 96 97
const COMPONENT_SELECTOR_PREFIX = 'uni-';
const COMPONENT_PREFIX = 'v-' + COMPONENT_SELECTOR_PREFIX;

fxy060608's avatar
fxy060608 已提交
98 99 100 101 102
const LINEFEED = '\n';
const NAVBAR_HEIGHT = 44;
const TABBAR_HEIGHT = 50;
const ON_REACH_BOTTOM_DISTANCE = 50;
const RESPONSIVE_MIN_WIDTH = 768;
fxy060608's avatar
fxy060608 已提交
103
const UNI_STORAGE_LOCALE = 'UNI_LOCALE';
fxy060608's avatar
fxy060608 已提交
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
// quickapp-webview 不能使用 default 作为插槽名称
const SLOT_DEFAULT_NAME = 'd';
const COMPONENT_NAME_PREFIX = 'VUni';
const I18N_JSON_DELIMITERS = ['%', '%'];
const PRIMARY_COLOR = '#007aff';
const SELECTED_COLOR = '#0062cc'; // 选中的颜色,如选项卡默认的选中颜色
const BACKGROUND_COLOR = '#f7f7f7'; // 背景色,如标题栏默认背景色
const UNI_SSR = '__uniSSR';
const UNI_SSR_TITLE = 'title';
const UNI_SSR_STORE = 'store';
const UNI_SSR_DATA = 'data';
const UNI_SSR_GLOBAL_DATA = 'globalData';
const SCHEME_RE = /^([a-z-]+:)?\/\//i;
const DATA_RE = /^data:.*,.*/;
const WEB_INVOKE_APPSERVICE = 'WEB_INVOKE_APPSERVICE';
const WXS_PROTOCOL = 'wxs://';
const JSON_PROTOCOL = 'json://';
const WXS_MODULES = 'wxsModules';
const RENDERJS_MODULES = 'renderjsModules';
// lifecycle
// App and Page
const ON_SHOW = 'onShow';
const ON_HIDE = 'onHide';
//App
const ON_LAUNCH = 'onLaunch';
const ON_ERROR = 'onError';
const ON_THEME_CHANGE = 'onThemeChange';
const ON_KEYBOARD_HEIGHT_CHANGE = 'onKeyboardHeightChange';
const ON_PAGE_NOT_FOUND = 'onPageNotFound';
const ON_UNHANDLE_REJECTION = 'onUnhandledRejection';
//Page
const ON_LOAD = 'onLoad';
const ON_READY = 'onReady';
const ON_UNLOAD = 'onUnload';
const ON_RESIZE = 'onResize';
const ON_BACK_PRESS = 'onBackPress';
const ON_PAGE_SCROLL = 'onPageScroll';
const ON_TAB_ITEM_TAP = 'onTabItemTap';
const ON_REACH_BOTTOM = 'onReachBottom';
const ON_PULL_DOWN_REFRESH = 'onPullDownRefresh';
const ON_SHARE_TIMELINE = 'onShareTimeline';
const ON_ADD_TO_FAVORITES = 'onAddToFavorites';
const ON_SHARE_APP_MESSAGE = 'onShareAppMessage';
// navigationBar
const ON_NAVIGATION_BAR_BUTTON_TAP = 'onNavigationBarButtonTap';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED = 'onNavigationBarSearchInputClicked';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED = 'onNavigationBarSearchInputChanged';
const ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED = 'onNavigationBarSearchInputConfirmed';
const ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED = 'onNavigationBarSearchInputFocusChanged';
// framework
const ON_APP_ENTER_FOREGROUND = 'onAppEnterForeground';
const ON_APP_ENTER_BACKGROUND = 'onAppEnterBackground';
const ON_WEB_INVOKE_APP_SERVICE = 'onWebInvokeAppService';
const ON_WXS_INVOKE_CALL_METHOD = 'onWxsInvokeCallMethod';

fxy060608's avatar
fxy060608 已提交
159 160 161 162 163 164 165 166 167 168 169
function resolveOwnerVm(vm) {
    if (!vm) {
        return;
    }
    let componentName = vm.type.name;
    while (componentName && isBuiltInComponent(hyphenate(componentName))) {
        // ownerInstance 内置组件需要使用父 vm
        vm = vm.parent;
        componentName = vm.type.name;
    }
    return vm.proxy;
fxy060608's avatar
fxy060608 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
}
function isElement(el) {
    // Element
    return el.nodeType === 1;
}
function resolveOwnerEl(instance) {
    const { vnode } = instance;
    if (isElement(vnode.el)) {
        return vnode.el;
    }
    const { subTree } = instance;
    // ShapeFlags.ARRAY_CHILDREN = 1<<4
    if (subTree.shapeFlag & 16) {
        const elemVNode = subTree.children.find((vnode) => isElement(vnode.el));
        if (elemVNode) {
            return elemVNode.el;
        }
    }
    return vnode.el;
fxy060608's avatar
fxy060608 已提交
189 190 191
}
function dynamicSlotName(name) {
    return name === 'default' ? SLOT_DEFAULT_NAME : name;
fxy060608's avatar
fxy060608 已提交
192
}
Q
qiang 已提交
193

fxy060608's avatar
fxy060608 已提交
194
let lastLogTime = 0;
fxy060608's avatar
fxy060608 已提交
195
function formatLog(module, ...args) {
fxy060608's avatar
fxy060608 已提交
196 197 198 199
    const now = Date.now();
    const diff = lastLogTime ? now - lastLogTime : 0;
    lastLogTime = now;
    return `[${now}][${diff}ms][${module}]:${args
fxy060608's avatar
fxy060608 已提交
200 201 202 203
        .map((arg) => JSON.stringify(arg))
        .join(' ')}`;
}

Q
qiang 已提交
204 205 206
function formatKey(key) {
    return camelize(key.substring(5));
}
Q
qiang 已提交
207
function initCustomDataset() {
Q
qiang 已提交
208 209 210 211
    const prototype = HTMLElement.prototype;
    const setAttribute = prototype.setAttribute;
    prototype.setAttribute = function (key, value) {
        if (key.startsWith('data-') && this.tagName.startsWith('UNI-')) {
fxy060608's avatar
fxy060608 已提交
212 213
            const dataset = this.__uniDataset ||
                (this.__uniDataset = {});
Q
qiang 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227
            dataset[formatKey(key)] = value;
        }
        setAttribute.call(this, key, value);
    };
    const removeAttribute = prototype.removeAttribute;
    prototype.removeAttribute = function (key) {
        if (this.__uniDataset &&
            key.startsWith('data-') &&
            this.tagName.startsWith('UNI-')) {
            delete this.__uniDataset[formatKey(key)];
        }
        removeAttribute.call(this, key);
    };
}
Q
qiang 已提交
228
function getCustomDataset(el) {
fxy060608's avatar
fxy060608 已提交
229
    return extend({}, el.dataset, el.__uniDataset);
Q
qiang 已提交
230
}
fxy060608's avatar
fxy060608 已提交
231

fxy060608's avatar
fxy060608 已提交
232 233 234 235 236 237 238 239 240 241 242
const unitRE = new RegExp(`"[^"]+"|'[^']+'|url\\([^)]+\\)|(\\d*\\.?\\d+)[r|u]px`, 'g');
function toFixed(number, precision) {
    const multiplier = Math.pow(10, precision + 1);
    const wholeNumber = Math.floor(number * multiplier);
    return (Math.round(wholeNumber / 10) * 10) / multiplier;
}
const defaultRpx2Unit = {
    unit: 'rem',
    unitRatio: 10 / 320,
    unitPrecision: 5,
};
fxy060608's avatar
fxy060608 已提交
243 244 245 246 247
const defaultMiniProgramRpx2Unit = {
    unit: 'rpx',
    unitRatio: 1,
    unitPrecision: 1,
};
fxy060608's avatar
fxy060608 已提交
248
function createRpx2Unit(unit, unitRatio, unitPrecision) {
Q
qiang 已提交
249
    // ignore: rpxCalcIncludeWidth
fxy060608's avatar
fxy060608 已提交
250 251 252 253
    return (val) => val.replace(unitRE, (m, $1) => {
        if (!$1) {
            return m;
        }
fxy060608's avatar
fxy060608 已提交
254 255 256
        if (unitRatio === 1) {
            return `${$1}${unit}`;
        }
fxy060608's avatar
fxy060608 已提交
257 258 259 260 261
        const value = toFixed(parseFloat($1) * unitRatio, unitPrecision);
        return value === 0 ? '0' : `${value}${unit}`;
    });
}

fxy060608's avatar
fxy060608 已提交
262 263 264 265 266 267
function passive(passive) {
    return { passive };
}
function normalizeDataset(el) {
    // TODO
    return JSON.parse(JSON.stringify(el.dataset || {}));
fxy060608's avatar
fxy060608 已提交
268 269 270 271 272
}
function normalizeTarget(el) {
    const { id, offsetTop, offsetLeft } = el;
    return {
        id,
Q
qiang 已提交
273
        dataset: getCustomDataset(el),
fxy060608's avatar
fxy060608 已提交
274 275 276
        offsetTop,
        offsetLeft,
    };
fxy060608's avatar
fxy060608 已提交
277 278 279 280 281 282
}
function addFont(family, source, desc) {
    const fonts = document.fonts;
    if (fonts) {
        const fontFace = new FontFace(family, source, desc);
        return fontFace.load().then(() => {
283
            fonts.add && fonts.add(fontFace);
fxy060608's avatar
fxy060608 已提交
284 285 286 287 288 289
        });
    }
    return new Promise((resolve) => {
        const style = document.createElement('style');
        const values = [];
        if (desc) {
290
            const { style, weight, stretch, unicodeRange, variant, featureSettings } = desc;
fxy060608's avatar
fxy060608 已提交
291 292 293 294 295 296 297 298 299 300 301
            style && values.push(`font-style:${style}`);
            weight && values.push(`font-weight:${weight}`);
            stretch && values.push(`font-stretch:${stretch}`);
            unicodeRange && values.push(`unicode-range:${unicodeRange}`);
            variant && values.push(`font-variant:${variant}`);
            featureSettings && values.push(`font-feature-settings:${featureSettings}`);
        }
        style.innerText = `@font-face{font-family:"${family}";src:${source};${values.join(';')}}`;
        document.head.appendChild(style);
        resolve();
    });
fxy060608's avatar
fxy060608 已提交
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
}
function scrollTo(scrollTop, duration) {
    if (isString(scrollTop)) {
        const el = document.querySelector(scrollTop);
        if (el) {
            scrollTop = el.getBoundingClientRect().top + window.pageYOffset;
        }
    }
    if (scrollTop < 0) {
        scrollTop = 0;
    }
    const documentElement = document.documentElement;
    const { clientHeight, scrollHeight } = documentElement;
    scrollTop = Math.min(scrollTop, scrollHeight - clientHeight);
    if (duration === 0) {
        // 部分浏览器(比如微信)中 scrollTop 的值需要通过 document.body 来控制
        documentElement.scrollTop = document.body.scrollTop = scrollTop;
        return;
    }
    if (window.scrollY === scrollTop) {
        return;
    }
    const scrollTo = (duration) => {
        if (duration <= 0) {
            window.scrollTo(0, scrollTop);
            return;
        }
        const distaince = scrollTop - window.scrollY;
        requestAnimationFrame(function () {
            window.scrollTo(0, window.scrollY + (distaince / duration) * 10);
            scrollTo(duration - 10);
        });
    };
    scrollTo(duration);
fxy060608's avatar
fxy060608 已提交
336 337
}

fxy060608's avatar
fxy060608 已提交
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
const encode = encodeURIComponent;
function stringifyQuery(obj, encodeStr = encode) {
    const res = obj
        ? Object.keys(obj)
            .map((key) => {
            let val = obj[key];
            if (typeof val === undefined || val === null) {
                val = '';
            }
            else if (isPlainObject(val)) {
                val = JSON.stringify(val);
            }
            return encodeStr(key) + '=' + encodeStr(val);
        })
            .filter((x) => x.length > 0)
            .join('&')
        : null;
    return res ? `?${res}` : '';
}
/**
 * Decode text using `decodeURIComponent`. Returns the original text if it
 * fails.
 *
 * @param text - string to decode
 * @returns decoded string
 */
function decode(text) {
    try {
        return decodeURIComponent('' + text);
    }
    catch (err) { }
    return '' + text;
}
function decodedQuery(query = {}) {
    const decodedQuery = {};
    Object.keys(query).forEach((name) => {
        try {
            decodedQuery[name] = decode(query[name]);
        }
        catch (e) {
            decodedQuery[name] = query[name];
        }
    });
    return decodedQuery;
}
const PLUS_RE = /\+/g; // %2B
/**
 * https://github.com/vuejs/vue-router-next/blob/master/src/query.ts
 * @internal
 *
 * @param search - search string to parse
 * @returns a query object
 */
function parseQuery(search) {
    const query = {};
    // avoid creating an object with an empty key and empty value
    // because of split('&')
    if (search === '' || search === '?')
        return query;
    const hasLeadingIM = search[0] === '?';
    const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&');
    for (let i = 0; i < searchParams.length; ++i) {
        // pre decode the + into space
        const searchParam = searchParams[i].replace(PLUS_RE, ' ');
        // allow the = character
        let eqPos = searchParam.indexOf('=');
        let key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
        let value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
        if (key in query) {
            // an extra variable for ts types
            let currentValue = query[key];
            if (!isArray(currentValue)) {
                currentValue = query[key] = [currentValue];
            }
            currentValue.push(value);
        }
        else {
            query[key] = value;
        }
    }
    return query;
}

function parseUrl(url) {
    const [path, querystring] = url.split('?', 2);
    return {
        path,
fxy060608's avatar
fxy060608 已提交
425
        query: parseQuery(querystring || ''),
fxy060608's avatar
fxy060608 已提交
426 427 428
    };
}

fxy060608's avatar
fxy060608 已提交
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
function isDebugMode() {
    // @ts-expect-error
    return typeof __channelId__ === 'string' && __channelId__;
}
function jsonStringifyReplacer(k, p) {
    switch (toRawType(p)) {
        case 'Function':
            return 'function() { [native code] }';
        default:
            return p;
    }
}
function normalizeLog(type, filename, args) {
    if (isDebugMode()) {
        args.push(filename.replace('at ', 'uni-app:///'));
        return console[type].apply(console, args);
    }
    const msgs = args.map(function (v) {
        const type = toTypeString(v).toLowerCase();
        if (type === '[object object]' || type === '[object array]') {
            try {
                v =
                    '---BEGIN:JSON---' +
                        JSON.stringify(v, jsonStringifyReplacer) +
                        '---END:JSON---';
            }
            catch (e) {
                v = type;
            }
        }
        else {
            if (v === null) {
                v = '---NULL---';
            }
            else if (v === undefined) {
                v = '---UNDEFINED---';
            }
            else {
                const vType = toRawType(v).toUpperCase();
                if (vType === 'NUMBER' || vType === 'BOOLEAN') {
                    v = '---BEGIN:' + vType + '---' + v + '---END:' + vType + '---';
                }
                else {
                    v = String(v);
                }
            }
        }
        return v;
    });
    return msgs.join('---COMMA---') + ' ' + filename;
}
function formatAppLog(type, filename, ...args) {
fxy060608's avatar
fxy060608 已提交
481 482
    const res = normalizeLog(type, filename, args);
    res && console[type](res);
fxy060608's avatar
fxy060608 已提交
483 484 485
}
function formatH5Log(type, filename, ...args) {
    console[type].apply(console, [...args, filename]);
fxy060608's avatar
fxy060608 已提交
486 487
}

fxy060608's avatar
fxy060608 已提交
488 489 490 491 492 493 494 495 496 497 498
let latestNodeId = 1;
class NVueTextNode {
    constructor(text) {
        this.instanceId = '';
        this.nodeId = latestNodeId++;
        this.parentNode = null;
        this.nodeType = 3;
        this.text = text;
    }
}

fxy060608's avatar
fxy060608 已提交
499 500 501 502 503 504 505 506 507 508
function plusReady(callback) {
    if (typeof callback !== 'function') {
        return;
    }
    if (window.plus) {
        return callback();
    }
    document.addEventListener('plusready', callback);
}

fxy060608's avatar
fxy060608 已提交
509 510 511 512 513 514 515
class DOMException extends Error {
    constructor(message) {
        super(message);
        this.name = 'DOMException';
    }
}

fxy060608's avatar
fxy060608 已提交
516 517 518 519 520 521 522 523 524 525 526 527
function normalizeEventType(type, options) {
    if (options) {
        if (options.capture) {
            type += 'Capture';
        }
        if (options.once) {
            type += 'Once';
        }
        if (options.passive) {
            type += 'Passive';
        }
    }
fxy060608's avatar
fxy060608 已提交
528 529 530 531
    return `on${capitalize(camelize(type))}`;
}
class UniEvent {
    constructor(type, opts) {
fxy060608's avatar
fxy060608 已提交
532 533 534 535
        this.defaultPrevented = false;
        this.timeStamp = Date.now();
        this._stop = false;
        this._end = false;
fxy060608's avatar
fxy060608 已提交
536
        this.type = type;
fxy060608's avatar
fxy060608 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549
        this.bubbles = !!opts.bubbles;
        this.cancelable = !!opts.cancelable;
    }
    preventDefault() {
        this.defaultPrevented = true;
    }
    stopImmediatePropagation() {
        this._end = this._stop = true;
    }
    stopPropagation() {
        this._stop = true;
    }
}
fxy060608's avatar
fxy060608 已提交
550 551 552 553 554 555 556 557 558 559 560 561
function createUniEvent(evt) {
    if (evt instanceof UniEvent) {
        return evt;
    }
    const [type] = parseEventName(evt.type);
    const uniEvent = new UniEvent(type, {
        bubbles: false,
        cancelable: false,
    });
    extend(uniEvent, evt);
    return uniEvent;
}
fxy060608's avatar
fxy060608 已提交
562
class UniEventTarget {
fxy060608's avatar
fxy060608 已提交
563 564 565
    constructor() {
        this.listeners = Object.create(null);
    }
fxy060608's avatar
fxy060608 已提交
566
    dispatchEvent(evt) {
fxy060608's avatar
fxy060608 已提交
567
        const listeners = this.listeners[evt.type];
fxy060608's avatar
fxy060608 已提交
568
        if (!listeners) {
fxy060608's avatar
fxy060608 已提交
569 570 571
            if ((process.env.NODE_ENV !== 'production')) {
                console.error(formatLog('dispatchEvent', this.nodeId), evt.type, 'not found');
            }
fxy060608's avatar
fxy060608 已提交
572 573
            return false;
        }
fxy060608's avatar
fxy060608 已提交
574 575
        // 格式化事件类型
        const event = createUniEvent(evt);
fxy060608's avatar
fxy060608 已提交
576 577
        const len = listeners.length;
        for (let i = 0; i < len; i++) {
fxy060608's avatar
fxy060608 已提交
578 579
            listeners[i].call(this, event);
            if (event._end) {
fxy060608's avatar
fxy060608 已提交
580 581 582
                break;
            }
        }
fxy060608's avatar
fxy060608 已提交
583
        return event.cancelable && event.defaultPrevented;
fxy060608's avatar
fxy060608 已提交
584 585
    }
    addEventListener(type, listener, options) {
fxy060608's avatar
fxy060608 已提交
586
        type = normalizeEventType(type, options);
fxy060608's avatar
fxy060608 已提交
587
        (this.listeners[type] || (this.listeners[type] = [])).push(listener);
fxy060608's avatar
fxy060608 已提交
588 589
    }
    removeEventListener(type, callback, options) {
fxy060608's avatar
fxy060608 已提交
590
        type = normalizeEventType(type, options);
fxy060608's avatar
fxy060608 已提交
591
        const listeners = this.listeners[type];
fxy060608's avatar
fxy060608 已提交
592 593 594 595 596 597 598 599
        if (!listeners) {
            return;
        }
        const index = listeners.indexOf(callback);
        if (index > -1) {
            listeners.splice(index, 1);
        }
    }
fxy060608's avatar
fxy060608 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612
}
const optionsModifierRE = /(?:Once|Passive|Capture)$/;
function parseEventName(name) {
    let options;
    if (optionsModifierRE.test(name)) {
        options = {};
        let m;
        while ((m = name.match(optionsModifierRE))) {
            name = name.slice(0, name.length - m[0].length);
            options[m[0].toLowerCase()] = true;
        }
    }
    return [hyphenate(name.slice(2)), options];
fxy060608's avatar
fxy060608 已提交
613 614
}

fxy060608's avatar
fxy060608 已提交
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
const EventModifierFlags = {
    stop: 1,
    prevent: 1 << 1,
    self: 1 << 2,
};
function encodeModifier(modifiers) {
    let flag = 0;
    if (modifiers.includes('stop')) {
        flag |= EventModifierFlags.stop;
    }
    if (modifiers.includes('prevent')) {
        flag |= EventModifierFlags.prevent;
    }
    if (modifiers.includes('self')) {
        flag |= EventModifierFlags.self;
    }
    return flag;
fxy060608's avatar
fxy060608 已提交
632 633
}

fxy060608's avatar
fxy060608 已提交
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
const NODE_TYPE_PAGE = 0;
const NODE_TYPE_ELEMENT = 1;
const NODE_TYPE_TEXT = 3;
const NODE_TYPE_COMMENT = 8;
function sibling(node, type) {
    const { parentNode } = node;
    if (!parentNode) {
        return null;
    }
    const { childNodes } = parentNode;
    return childNodes[childNodes.indexOf(node) + (type === 'n' ? 1 : -1)] || null;
}
function removeNode(node) {
    const { parentNode } = node;
    if (parentNode) {
        parentNode.removeChild(node);
    }
}
function checkNodeId(node) {
fxy060608's avatar
fxy060608 已提交
653
    if (!node.nodeId && node.pageNode) {
fxy060608's avatar
fxy060608 已提交
654 655 656
        node.nodeId = node.pageNode.genId();
    }
}
fxy060608's avatar
fxy060608 已提交
657
// 为优化性能,各平台不使用proxy来实现node的操作拦截,而是直接通过pageNode定制
fxy060608's avatar
fxy060608 已提交
658
class UniNode extends UniEventTarget {
fxy060608's avatar
fxy060608 已提交
659
    constructor(nodeType, nodeName, container) {
fxy060608's avatar
fxy060608 已提交
660
        super();
fxy060608's avatar
fxy060608 已提交
661 662 663
        this.pageNode = null;
        this.parentNode = null;
        this._text = null;
fxy060608's avatar
fxy060608 已提交
664 665
        if (container) {
            const { pageNode } = container;
fxy060608's avatar
fxy060608 已提交
666 667 668
            if (pageNode) {
                this.pageNode = pageNode;
                this.nodeId = pageNode.genId();
fxy060608's avatar
fxy060608 已提交
669
                !pageNode.isUnmounted && pageNode.onCreate(this, nodeName);
fxy060608's avatar
fxy060608 已提交
670
            }
fxy060608's avatar
fxy060608 已提交
671
        }
fxy060608's avatar
fxy060608 已提交
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
        this.nodeType = nodeType;
        this.nodeName = nodeName;
        this.childNodes = [];
    }
    get firstChild() {
        return this.childNodes[0] || null;
    }
    get lastChild() {
        const { childNodes } = this;
        const length = childNodes.length;
        return length ? childNodes[length - 1] : null;
    }
    get nextSibling() {
        return sibling(this, 'n');
    }
fxy060608's avatar
fxy060608 已提交
687 688 689 690
    get nodeValue() {
        return null;
    }
    set nodeValue(_val) { }
fxy060608's avatar
fxy060608 已提交
691 692 693 694 695
    get textContent() {
        return this._text || '';
    }
    set textContent(text) {
        this._text = text;
fxy060608's avatar
fxy060608 已提交
696
        if (this.pageNode && !this.pageNode.isUnmounted) {
fxy060608's avatar
fxy060608 已提交
697 698
            this.pageNode.onTextContent(this, text);
        }
fxy060608's avatar
fxy060608 已提交
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    }
    get parentElement() {
        const { parentNode } = this;
        if (parentNode && parentNode.nodeType === NODE_TYPE_ELEMENT) {
            return parentNode;
        }
        return null;
    }
    get previousSibling() {
        return sibling(this, 'p');
    }
    appendChild(newChild) {
        return this.insertBefore(newChild, null);
    }
    cloneNode(deep) {
        const cloned = extend(Object.create(Object.getPrototypeOf(this)), this);
        const { attributes } = cloned;
        if (attributes) {
            cloned.attributes = extend({}, attributes);
        }
        if (deep) {
            cloned.childNodes = cloned.childNodes.map((childNode) => childNode.cloneNode(true));
        }
        return cloned;
    }
    insertBefore(newChild, refChild) {
        removeNode(newChild);
        newChild.pageNode = this.pageNode;
        newChild.parentNode = this;
        checkNodeId(newChild);
        const { childNodes } = this;
        if (refChild) {
fxy060608's avatar
fxy060608 已提交
731
            const index = childNodes.indexOf(refChild);
fxy060608's avatar
fxy060608 已提交
732 733 734
            if (index === -1) {
                throw new DOMException(`Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.`);
            }
fxy060608's avatar
fxy060608 已提交
735
            childNodes.splice(index, 0, newChild);
fxy060608's avatar
fxy060608 已提交
736 737 738 739
        }
        else {
            childNodes.push(newChild);
        }
fxy060608's avatar
fxy060608 已提交
740
        return this.pageNode && !this.pageNode.isUnmounted
fxy060608's avatar
fxy060608 已提交
741
            ? this.pageNode.onInsertBefore(this, newChild, refChild)
fxy060608's avatar
fxy060608 已提交
742
            : newChild;
fxy060608's avatar
fxy060608 已提交
743 744 745 746 747 748 749 750 751
    }
    removeChild(oldChild) {
        const { childNodes } = this;
        const index = childNodes.indexOf(oldChild);
        if (index === -1) {
            throw new DOMException(`Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.`);
        }
        oldChild.parentNode = null;
        childNodes.splice(index, 1);
fxy060608's avatar
fxy060608 已提交
752 753 754
        return this.pageNode && !this.pageNode.isUnmounted
            ? this.pageNode.onRemoveChild(oldChild)
            : oldChild;
fxy060608's avatar
fxy060608 已提交
755 756
    }
}
fxy060608's avatar
fxy060608 已提交
757 758
const ATTR_CLASS = 'class';
const ATTR_STYLE = 'style';
fxy060608's avatar
fxy060608 已提交
759 760
const ATTR_INNER_HTML = 'innerHTML';
const ATTR_TEXT_CONTENT = 'textContent';
fxy060608's avatar
fxy060608 已提交
761
const ATTR_V_SHOW = '.vShow';
fxy060608's avatar
fxy060608 已提交
762
const ATTR_V_OWNER_ID = '.vOwnerId';
fxy060608's avatar
fxy060608 已提交
763
const ATTR_V_RENDERJS = '.vRenderjs';
fxy060608's avatar
fxy060608 已提交
764
const ATTR_CHANGE_PREFIX = 'change:';
fxy060608's avatar
fxy060608 已提交
765
class UniBaseNode extends UniNode {
fxy060608's avatar
fxy060608 已提交
766 767
    constructor(nodeType, nodeName, container) {
        super(nodeType, nodeName, container);
fxy060608's avatar
fxy060608 已提交
768 769
        this.attributes = Object.create(null);
        this.style = null;
fxy060608's avatar
fxy060608 已提交
770
        this.vShow = null;
fxy060608's avatar
fxy060608 已提交
771
        this._html = null;
fxy060608's avatar
fxy060608 已提交
772 773
    }
    get className() {
fxy060608's avatar
fxy060608 已提交
774
        return (this.attributes[ATTR_CLASS] || '');
fxy060608's avatar
fxy060608 已提交
775 776
    }
    set className(val) {
fxy060608's avatar
fxy060608 已提交
777
        this.setAttribute(ATTR_CLASS, val);
fxy060608's avatar
fxy060608 已提交
778 779 780 781 782 783 784 785 786
    }
    get innerHTML() {
        return '';
    }
    set innerHTML(html) {
        this._html = html;
    }
    addEventListener(type, listener, options) {
        super.addEventListener(type, listener, options);
fxy060608's avatar
fxy060608 已提交
787
        if (this.pageNode && !this.pageNode.isUnmounted) {
fxy060608's avatar
fxy060608 已提交
788 789 790 791 792 793
            if (listener.wxsEvent) {
                this.pageNode.onAddWxsEvent(this, normalizeEventType(type, options), listener.wxsEvent, encodeModifier(listener.modifiers || []));
            }
            else {
                this.pageNode.onAddEvent(this, normalizeEventType(type, options), encodeModifier(listener.modifiers || []));
            }
fxy060608's avatar
fxy060608 已提交
794
        }
fxy060608's avatar
fxy060608 已提交
795 796 797
    }
    removeEventListener(type, callback, options) {
        super.removeEventListener(type, callback, options);
fxy060608's avatar
fxy060608 已提交
798
        if (this.pageNode && !this.pageNode.isUnmounted) {
fxy060608's avatar
fxy060608 已提交
799
            this.pageNode.onRemoveEvent(this, normalizeEventType(type, options));
fxy060608's avatar
fxy060608 已提交
800
        }
fxy060608's avatar
fxy060608 已提交
801 802
    }
    getAttribute(qualifiedName) {
fxy060608's avatar
fxy060608 已提交
803 804 805
        if (qualifiedName === ATTR_STYLE) {
            return this.style;
        }
fxy060608's avatar
fxy060608 已提交
806
        return this.attributes[qualifiedName];
fxy060608's avatar
fxy060608 已提交
807 808
    }
    removeAttribute(qualifiedName) {
fxy060608's avatar
fxy060608 已提交
809 810 811 812 813 814
        if (qualifiedName == ATTR_STYLE) {
            this.style = null;
        }
        else {
            delete this.attributes[qualifiedName];
        }
fxy060608's avatar
fxy060608 已提交
815
        if (this.pageNode && !this.pageNode.isUnmounted) {
fxy060608's avatar
fxy060608 已提交
816 817
            this.pageNode.onRemoveAttribute(this, qualifiedName);
        }
fxy060608's avatar
fxy060608 已提交
818 819
    }
    setAttribute(qualifiedName, value) {
fxy060608's avatar
fxy060608 已提交
820 821 822 823 824 825
        if (qualifiedName === ATTR_STYLE) {
            this.style = value;
        }
        else {
            this.attributes[qualifiedName] = value;
        }
fxy060608's avatar
fxy060608 已提交
826
        if (this.pageNode && !this.pageNode.isUnmounted) {
fxy060608's avatar
fxy060608 已提交
827 828
            this.pageNode.onSetAttribute(this, qualifiedName, value);
        }
fxy060608's avatar
fxy060608 已提交
829
    }
fxy060608's avatar
fxy060608 已提交
830
    toJSON({ attr, normalize, } = {}) {
fxy060608's avatar
fxy060608 已提交
831
        const { attributes, style, listeners, _text } = this;
fxy060608's avatar
fxy060608 已提交
832 833
        const res = {};
        if (Object.keys(attributes).length) {
fxy060608's avatar
fxy060608 已提交
834
            res.a = normalize ? normalize(attributes) : attributes;
fxy060608's avatar
fxy060608 已提交
835
        }
fxy060608's avatar
fxy060608 已提交
836 837
        const events = Object.keys(listeners);
        if (events.length) {
fxy060608's avatar
fxy060608 已提交
838
            let w = undefined;
fxy060608's avatar
fxy060608 已提交
839 840 841 842 843
            const e = {};
            events.forEach((name) => {
                const handlers = listeners[name];
                if (handlers.length) {
                    // 可能存在多个 handler 且不同 modifiers 吗?
fxy060608's avatar
fxy060608 已提交
844 845 846 847 848 849 850 851 852 853 854
                    const { wxsEvent, modifiers } = handlers[0];
                    const modifier = encodeModifier(modifiers || []);
                    if (!wxsEvent) {
                        e[name] = modifier;
                    }
                    else {
                        if (!w) {
                            w = {};
                        }
                        w[name] = [normalize ? normalize(wxsEvent) : wxsEvent, modifier];
                    }
fxy060608's avatar
fxy060608 已提交
855 856
                }
            });
fxy060608's avatar
fxy060608 已提交
857
            res.e = normalize ? normalize(e, false) : e;
fxy060608's avatar
fxy060608 已提交
858 859 860
            if (w) {
                res.w = normalize ? normalize(w, false) : w;
            }
fxy060608's avatar
fxy060608 已提交
861
        }
fxy060608's avatar
fxy060608 已提交
862 863
        if (style !== null) {
            res.s = normalize ? normalize(style) : style;
fxy060608's avatar
fxy060608 已提交
864
        }
fxy060608's avatar
fxy060608 已提交
865
        if (!attr) {
fxy060608's avatar
fxy060608 已提交
866
            res.i = this.nodeId;
fxy060608's avatar
fxy060608 已提交
867
            res.n = this.nodeName;
fxy060608's avatar
fxy060608 已提交
868
        }
fxy060608's avatar
fxy060608 已提交
869 870
        if (_text !== null) {
            res.t = normalize ? normalize(_text) : _text;
fxy060608's avatar
fxy060608 已提交
871 872 873 874 875 876
        }
        return res;
    }
}

class UniCommentNode extends UniNode {
fxy060608's avatar
fxy060608 已提交
877 878
    constructor(text, container) {
        super(NODE_TYPE_COMMENT, '#comment', container);
fxy060608's avatar
fxy060608 已提交
879
        this._text = (process.env.NODE_ENV !== 'production') ? text : '';
fxy060608's avatar
fxy060608 已提交
880
    }
fxy060608's avatar
fxy060608 已提交
881
    toJSON(opts = {}) {
fxy060608's avatar
fxy060608 已提交
882
        // 暂时不传递 text 到 view 层,没啥意义,节省点数据量
fxy060608's avatar
fxy060608 已提交
883
        return opts.attr
fxy060608's avatar
fxy060608 已提交
884
            ? {}
fxy060608's avatar
fxy060608 已提交
885 886 887
            : {
                i: this.nodeId,
            };
fxy060608's avatar
fxy060608 已提交
888 889 890 891 892 893
        // return opts.attr
        //   ? { t: this._text as string }
        //   : {
        //       i: this.nodeId!,
        //       t: this._text as string,
        //     }
fxy060608's avatar
fxy060608 已提交
894
    }
fxy060608's avatar
fxy060608 已提交
895 896 897
}

class UniElement extends UniBaseNode {
fxy060608's avatar
fxy060608 已提交
898 899
    constructor(nodeName, container) {
        super(NODE_TYPE_ELEMENT, nodeName.toUpperCase(), container);
fxy060608's avatar
fxy060608 已提交
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
        this.tagName = this.nodeName;
    }
}
class UniInputElement extends UniElement {
    get value() {
        return this.getAttribute('value');
    }
    set value(val) {
        this.setAttribute('value', val);
    }
}
class UniTextAreaElement extends UniInputElement {
}

class UniTextNode extends UniBaseNode {
fxy060608's avatar
fxy060608 已提交
915 916
    constructor(text, container) {
        super(NODE_TYPE_TEXT, '#text', container);
fxy060608's avatar
fxy060608 已提交
917 918 919 920 921 922 923
        this._text = text;
    }
    get nodeValue() {
        return this._text || '';
    }
    set nodeValue(text) {
        this._text = text;
fxy060608's avatar
fxy060608 已提交
924
        if (this.pageNode && !this.pageNode.isUnmounted) {
fxy060608's avatar
fxy060608 已提交
925 926
            this.pageNode.onNodeValue(this, text);
        }
fxy060608's avatar
fxy060608 已提交
927 928 929
    }
}

fxy060608's avatar
fxy060608 已提交
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
const forcePatchProps = {
    AD: ['data'],
    'AD-DRAW': ['data'],
    'LIVE-PLAYER': ['picture-in-picture-mode'],
    MAP: [
        'markers',
        'polyline',
        'circles',
        'controls',
        'include-points',
        'polygons',
    ],
    PICKER: ['range', 'value'],
    'PICKER-VIEW': ['value'],
    'RICH-TEXT': ['nodes'],
    VIDEO: ['danmu-list', 'header'],
    'WEB-VIEW': ['webview-styles'],
};
const forcePatchPropKeys = ['animation'];

const forcePatchProp = (el, key) => {
    if (forcePatchPropKeys.indexOf(key) > -1) {
        return true;
    }
    const keys = forcePatchProps[el.nodeName];
    if (keys && keys.indexOf(key) > -1) {
        return true;
    }
    return false;
};

fxy060608's avatar
fxy060608 已提交
961 962 963 964 965 966 967 968 969 970
const ACTION_TYPE_PAGE_CREATE = 1;
const ACTION_TYPE_PAGE_CREATED = 2;
const ACTION_TYPE_CREATE = 3;
const ACTION_TYPE_INSERT = 4;
const ACTION_TYPE_REMOVE = 5;
const ACTION_TYPE_SET_ATTRIBUTE = 6;
const ACTION_TYPE_REMOVE_ATTRIBUTE = 7;
const ACTION_TYPE_ADD_EVENT = 8;
const ACTION_TYPE_REMOVE_EVENT = 9;
const ACTION_TYPE_SET_TEXT = 10;
fxy060608's avatar
fxy060608 已提交
971
const ACTION_TYPE_ADD_WXS_EVENT = 12;
fxy060608's avatar
fxy060608 已提交
972
const ACTION_TYPE_PAGE_SCROLL = 15;
fxy060608's avatar
fxy060608 已提交
973 974
const ACTION_TYPE_EVENT = 20;

fxy060608's avatar
fxy060608 已提交
975
function cache(fn) {
fxy060608's avatar
fxy060608 已提交
976
    const cache = Object.create(null);
fxy060608's avatar
fxy060608 已提交
977
    return (str) => {
fxy060608's avatar
fxy060608 已提交
978 979
        const hit = cache[str];
        return hit || (cache[str] = fn(str));
fxy060608's avatar
fxy060608 已提交
980 981 982 983 984
    };
}
function cacheStringFunction(fn) {
    return cache(fn);
}
fxy060608's avatar
fxy060608 已提交
985 986
function getLen(str = '') {
    return ('' + str).replace(/[^\x00-\xff]/g, '**').length;
fxy060608's avatar
fxy060608 已提交
987
}
fxy060608's avatar
fxy060608 已提交
988 989 990 991 992 993
function hasLeadingSlash(str) {
    return str.indexOf('/') === 0;
}
function addLeadingSlash(str) {
    return hasLeadingSlash(str) ? str : '/' + str;
}
fxy060608's avatar
fxy060608 已提交
994
function removeLeadingSlash(str) {
fxy060608's avatar
fxy060608 已提交
995
    return hasLeadingSlash(str) ? str.substr(1) : str;
fxy060608's avatar
fxy060608 已提交
996 997 998 999 1000 1001 1002
}
const invokeArrayFns = (fns, arg) => {
    let ret;
    for (let i = 0; i < fns.length; i++) {
        ret = fns[i](arg);
    }
    return ret;
fxy060608's avatar
fxy060608 已提交
1003 1004 1005 1006 1007
};
function updateElementStyle(element, styles) {
    for (const attrName in styles) {
        element.style[attrName] = styles[attrName];
    }
fxy060608's avatar
fxy060608 已提交
1008 1009 1010
}
function once(fn, ctx = null) {
    let res;
fxy060608's avatar
fxy060608 已提交
1011
    return ((...args) => {
fxy060608's avatar
fxy060608 已提交
1012 1013 1014 1015 1016
        if (fn) {
            res = fn.apply(ctx, args);
            fn = null;
        }
        return res;
fxy060608's avatar
fxy060608 已提交
1017
    });
fxy060608's avatar
fxy060608 已提交
1018
}
D
DCloud_LXH 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
const sanitise = (val) => (val && JSON.parse(JSON.stringify(val))) || val;
const _completeValue = (value) => (value > 9 ? value : '0' + value);
function formatDateTime({ date = new Date(), mode = 'date' }) {
    if (mode === 'time') {
        return (_completeValue(date.getHours()) + ':' + _completeValue(date.getMinutes()));
    }
    else {
        return (date.getFullYear() +
            '-' +
            _completeValue(date.getMonth() + 1) +
            '-' +
            _completeValue(date.getDate()));
    }
Q
qiang 已提交
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
}
function callOptions(options, data) {
    options = options || {};
    if (typeof data === 'string') {
        data = {
            errMsg: data,
        };
    }
    if (/:ok$/.test(data.errMsg)) {
        if (typeof options.success === 'function') {
            options.success(data);
        }
    }
    else {
        if (typeof options.fail === 'function') {
            options.fail(data);
        }
    }
    if (typeof options.complete === 'function') {
        options.complete(data);
    }
fxy060608's avatar
fxy060608 已提交
1053 1054
}
function getValueByDataPath(obj, path) {
fxy060608's avatar
fxy060608 已提交
1055 1056 1057 1058
    if (!isString(path)) {
        return;
    }
    path = path.replace(/\[(\d+)\]/g, '.$1');
fxy060608's avatar
fxy060608 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067
    const parts = path.split('.');
    let key = parts[0];
    if (!obj) {
        obj = {};
    }
    if (parts.length === 1) {
        return obj[key];
    }
    return getValueByDataPath(obj[key], parts.slice(1).join('.'));
D
DCloud_LXH 已提交
1068
}
fxy060608's avatar
fxy060608 已提交
1069

fxy060608's avatar
fxy060608 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
function debounce(fn, delay) {
    let timeout;
    const newFn = function () {
        clearTimeout(timeout);
        const timerFn = () => fn.apply(this, arguments);
        timeout = setTimeout(timerFn, delay);
    };
    newFn.cancel = function () {
        clearTimeout(timeout);
    };
    return newFn;
}

fxy060608's avatar
fxy060608 已提交
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
class EventChannel {
    constructor(id, events) {
        this.id = id;
        this.listener = {};
        this.emitCache = {};
        if (events) {
            Object.keys(events).forEach((name) => {
                this.on(name, events[name]);
            });
        }
    }
    emit(eventName, ...args) {
        const fns = this.listener[eventName];
        if (!fns) {
            return (this.emitCache[eventName] || (this.emitCache[eventName] = [])).push(args);
        }
        fns.forEach((opt) => {
            opt.fn.apply(opt.fn, args);
        });
        this.listener[eventName] = fns.filter((opt) => opt.type !== 'once');
    }
    on(eventName, fn) {
        this._addListener(eventName, 'on', fn);
        this._clearCache(eventName);
    }
    once(eventName, fn) {
        this._addListener(eventName, 'once', fn);
        this._clearCache(eventName);
    }
    off(eventName, fn) {
        const fns = this.listener[eventName];
        if (!fns) {
            return;
        }
        if (fn) {
            for (let i = 0; i < fns.length;) {
                if (fns[i].fn === fn) {
                    fns.splice(i, 1);
                    i--;
                }
                i++;
            }
        }
        else {
            delete this.listener[eventName];
        }
    }
    _clearCache(eventName) {
        const cacheArgs = this.emitCache[eventName];
        if (cacheArgs) {
            for (; cacheArgs.length > 0;) {
                this.emit.apply(this, [eventName, ...cacheArgs.shift()]);
            }
        }
    }
    _addListener(eventName, type, fn) {
        (this.listener[eventName] || (this.listener[eventName] = [])).push({
            fn,
            type,
        });
    }
}

fxy060608's avatar
fxy060608 已提交
1146
const PAGE_HOOKS = [
1147
    ON_LOAD,
1148 1149
    ON_SHOW,
    ON_HIDE,
1150
    ON_UNLOAD,
fxy060608's avatar
fxy060608 已提交
1151 1152 1153 1154 1155
    ON_BACK_PRESS,
    ON_PAGE_SCROLL,
    ON_TAB_ITEM_TAP,
    ON_REACH_BOTTOM,
    ON_PULL_DOWN_REFRESH,
1156 1157 1158 1159 1160 1161 1162 1163
    ON_SHARE_TIMELINE,
    ON_SHARE_APP_MESSAGE,
    ON_ADD_TO_FAVORITES,
    ON_NAVIGATION_BAR_BUTTON_TAP,
    ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED,
    ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED,
    ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED,
    ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED,
fxy060608's avatar
fxy060608 已提交
1164 1165 1166
];
function isRootHook(name) {
    return PAGE_HOOKS.indexOf(name) > -1;
fxy060608's avatar
fxy060608 已提交
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
}
const UniLifecycleHooks = [
    ON_SHOW,
    ON_HIDE,
    ON_LAUNCH,
    ON_ERROR,
    ON_THEME_CHANGE,
    ON_PAGE_NOT_FOUND,
    ON_UNHANDLE_REJECTION,
    ON_LOAD,
    ON_READY,
    ON_UNLOAD,
    ON_RESIZE,
    ON_BACK_PRESS,
    ON_PAGE_SCROLL,
    ON_TAB_ITEM_TAP,
    ON_REACH_BOTTOM,
    ON_PULL_DOWN_REFRESH,
    ON_SHARE_TIMELINE,
    ON_ADD_TO_FAVORITES,
    ON_SHARE_APP_MESSAGE,
    ON_NAVIGATION_BAR_BUTTON_TAP,
    ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED,
    ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED,
    ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED,
    ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED,
];
fxy060608's avatar
fxy060608 已提交
1194

fxy060608's avatar
fxy060608 已提交
1195 1196 1197 1198 1199 1200
function getEnvLocale() {
    const { env } = process;
    const lang = env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE;
    return (lang && lang.replace(/[.:].*/, '')) || 'en';
}

1201
export { ACTION_TYPE_ADD_EVENT, ACTION_TYPE_ADD_WXS_EVENT, ACTION_TYPE_CREATE, ACTION_TYPE_EVENT, ACTION_TYPE_INSERT, ACTION_TYPE_PAGE_CREATE, ACTION_TYPE_PAGE_CREATED, ACTION_TYPE_PAGE_SCROLL, ACTION_TYPE_REMOVE, ACTION_TYPE_REMOVE_ATTRIBUTE, ACTION_TYPE_REMOVE_EVENT, ACTION_TYPE_SET_ATTRIBUTE, ACTION_TYPE_SET_TEXT, ATTR_CHANGE_PREFIX, ATTR_CLASS, ATTR_INNER_HTML, ATTR_STYLE, ATTR_TEXT_CONTENT, ATTR_V_OWNER_ID, ATTR_V_RENDERJS, ATTR_V_SHOW, BACKGROUND_COLOR, BUILT_IN_TAGS, BUILT_IN_TAG_NAMES, COMPONENT_NAME_PREFIX, COMPONENT_PREFIX, COMPONENT_SELECTOR_PREFIX, DATA_RE, EventChannel, EventModifierFlags, I18N_JSON_DELIMITERS, JSON_PROTOCOL, LINEFEED, NAVBAR_HEIGHT, NODE_TYPE_COMMENT, NODE_TYPE_ELEMENT, NODE_TYPE_PAGE, NODE_TYPE_TEXT, NVueTextNode, ON_ADD_TO_FAVORITES, ON_APP_ENTER_BACKGROUND, ON_APP_ENTER_FOREGROUND, ON_BACK_PRESS, ON_ERROR, ON_HIDE, ON_KEYBOARD_HEIGHT_CHANGE, ON_LAUNCH, ON_LOAD, ON_NAVIGATION_BAR_BUTTON_TAP, ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, ON_PAGE_NOT_FOUND, ON_PAGE_SCROLL, ON_PULL_DOWN_REFRESH, ON_REACH_BOTTOM, ON_REACH_BOTTOM_DISTANCE, ON_READY, ON_RESIZE, ON_SHARE_APP_MESSAGE, ON_SHARE_TIMELINE, ON_SHOW, ON_TAB_ITEM_TAP, ON_THEME_CHANGE, ON_UNHANDLE_REJECTION, ON_UNLOAD, ON_WEB_INVOKE_APP_SERVICE, ON_WXS_INVOKE_CALL_METHOD, PLUS_RE, PRIMARY_COLOR, RENDERJS_MODULES, RESPONSIVE_MIN_WIDTH, SCHEME_RE, SELECTED_COLOR, SLOT_DEFAULT_NAME, TABBAR_HEIGHT, TAGS, UNI_SSR, UNI_SSR_DATA, UNI_SSR_GLOBAL_DATA, UNI_SSR_STORE, UNI_SSR_TITLE, UNI_STORAGE_LOCALE, UniBaseNode, UniCommentNode, UniElement, UniEvent, UniInputElement, UniLifecycleHooks, UniNode, UniTextAreaElement, UniTextNode, WEB_INVOKE_APPSERVICE, WXS_MODULES, WXS_PROTOCOL, addFont, addLeadingSlash, cache, cacheStringFunction, callOptions, createIsCustomElement, createRpx2Unit, createUniEvent, debounce, decode, decodedQuery, defaultMiniProgramRpx2Unit, defaultRpx2Unit, dynamicSlotName, forcePatchProp, formatAppLog, formatDateTime, formatH5Log, formatLog, getCustomDataset, getEnvLocale, getLen, getValueByDataPath, initCustomDataset, invokeArrayFns, isAppNativeTag, isBuiltInComponent, isComponentTag, isH5CustomElement, isH5NativeTag, isMiniProgramNativeTag, isRootHook, normalizeDataset, normalizeEventType, normalizeTarget, once, parseEventName, parseQuery, parseUrl, passive, plusReady, removeLeadingSlash, resolveOwnerEl, resolveOwnerVm, sanitise, scrollTo, stringifyQuery, updateElementStyle };