uni-shared.cjs.js 27.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var shared = require('@vue/shared');

Q
qiang 已提交
7 8 9
function formatKey(key) {
    return shared.camelize(key.substring(5));
}
Q
qiang 已提交
10
function initCustomDataset() {
Q
qiang 已提交
11 12 13 14
    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 已提交
15 16
            const dataset = this.__uniDataset ||
                (this.__uniDataset = {});
Q
qiang 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30
            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 已提交
31
function getCustomDataset(el) {
fxy060608's avatar
fxy060608 已提交
32
    return shared.extend({}, el.dataset, el.__uniDataset);
Q
qiang 已提交
33 34
}

fxy060608's avatar
fxy060608 已提交
35 36 37 38 39 40 41 42 43 44 45 46
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,
};
function createRpx2Unit(unit, unitRatio, unitPrecision) {
Q
qiang 已提交
47
    // ignore: rpxCalcIncludeWidth
fxy060608's avatar
fxy060608 已提交
48 49 50 51 52 53 54 55 56
    return (val) => val.replace(unitRE, (m, $1) => {
        if (!$1) {
            return m;
        }
        const value = toFixed(parseFloat($1) * unitRatio, unitPrecision);
        return value === 0 ? '0' : `${value}${unit}`;
    });
}

fxy060608's avatar
fxy060608 已提交
57 58 59 60 61 62
function passive(passive) {
    return { passive };
}
function normalizeDataset(el) {
    // TODO
    return JSON.parse(JSON.stringify(el.dataset || {}));
fxy060608's avatar
fxy060608 已提交
63 64 65 66 67
}
function normalizeTarget(el) {
    const { id, offsetTop, offsetLeft } = el;
    return {
        id,
Q
qiang 已提交
68
        dataset: getCustomDataset(el),
fxy060608's avatar
fxy060608 已提交
69 70 71
        offsetTop,
        offsetLeft,
    };
fxy060608's avatar
fxy060608 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84
}
function addFont(family, source, desc) {
    const fonts = document.fonts;
    if (fonts) {
        const fontFace = new FontFace(family, source, desc);
        return fontFace.load().then(() => {
            fonts.add(fontFace);
        });
    }
    return new Promise((resolve) => {
        const style = document.createElement('style');
        const values = [];
        if (desc) {
85
            const { style, weight, stretch, unicodeRange, variant, featureSettings } = desc;
fxy060608's avatar
fxy060608 已提交
86 87 88 89 90 91 92 93 94 95 96
            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 已提交
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
}
function scrollTo(scrollTop, duration) {
    if (shared.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 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143
}

function plusReady(callback) {
    if (typeof callback !== 'function') {
        return;
    }
    if (window.plus) {
        return callback();
    }
    document.addEventListener('plusready', callback);
}

const BUILT_IN_TAGS = [
fxy060608's avatar
fxy060608 已提交
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
    'ad',
    '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',
].map((tag) => 'uni-' + tag);
fxy060608's avatar
fxy060608 已提交
186
const TAGS = [
fxy060608's avatar
fxy060608 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    '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);
fxy060608's avatar
fxy060608 已提交
206 207 208 209 210 211 212 213 214
function isBuiltInComponent(tag) {
    return BUILT_IN_TAGS.indexOf('uni-' + tag) !== -1;
}
function isCustomElement(tag) {
    return TAGS.indexOf(tag) !== -1 || BUILT_IN_TAGS.indexOf(tag) !== -1;
}
function isNativeTag(tag) {
    return (shared.isHTMLTag(tag) || shared.isSVGTag(tag)) && !isBuiltInComponent(tag);
}
fxy060608's avatar
fxy060608 已提交
215 216 217 218 219 220
function isServiceNativeTag(tag) {
    return shared.isHTMLTag(tag) || shared.isSVGTag(tag) || isBuiltInComponent(tag);
}
function isServiceCustomElement(_tag) {
    return false;
}
fxy060608's avatar
fxy060608 已提交
221 222
const COMPONENT_SELECTOR_PREFIX = 'uni-';
const COMPONENT_PREFIX = 'v-' + COMPONENT_SELECTOR_PREFIX;
fxy060608's avatar
fxy060608 已提交
223

fxy060608's avatar
fxy060608 已提交
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
class DOMException extends Error {
    constructor(message) {
        super(message);
        this.name = 'DOMException';
    }
}

function normalizeEventType(type) {
    return `on${shared.capitalize(shared.camelize(type))}`;
}
class UniEvent {
    constructor(type, opts) {
        this.defaultPrevented = false;
        this.timeStamp = Date.now();
        this._stop = false;
        this._end = false;
        this.type = type.toLowerCase();
        this.bubbles = !!opts.bubbles;
        this.cancelable = !!opts.cancelable;
    }
    preventDefault() {
        this.defaultPrevented = true;
    }
    stopImmediatePropagation() {
        this._end = this._stop = true;
    }
    stopPropagation() {
        this._stop = true;
    }
}
class UniEventTarget {
    constructor() {
        this._listeners = {};
    }
    dispatchEvent(evt) {
        const listeners = this._listeners[evt.type];
        if (!listeners) {
            return false;
        }
        const len = listeners.length;
        for (let i = 0; i < len; i++) {
            listeners[i].call(this, evt);
            if (evt._end) {
                break;
            }
        }
        return evt.cancelable && evt.defaultPrevented;
    }
    addEventListener(type, listener, options) {
        const isOnce = options && options.once;
        if (isOnce) {
            const wrapper = function (evt) {
                listener.apply(this, [evt]);
                this.removeEventListener(type, wrapper, options);
            };
            return this.addEventListener(type, wrapper, shared.extend(options, { once: false }));
        }
        (this._listeners[type] || (this._listeners[type] = [])).push(listener);
    }
    removeEventListener(type, callback, options) {
        const listeners = this._listeners[type.toLowerCase()];
        if (!listeners) {
            return;
        }
        const index = listeners.indexOf(callback);
        if (index > -1) {
            listeners.splice(index, 1);
        }
    }
}

class UniCSSStyleDeclaration {
    constructor() {
        this._cssText = null;
        this._value = null;
    }
    setProperty(property, value) {
        if (value === null || value === '') {
            this.removeProperty(property);
        }
        else {
            if (!this._value) {
                this._value = {};
            }
            this._value[property] = value;
        }
    }
    getPropertyValue(property) {
        if (!this._value) {
            return '';
        }
        return this._value[property] || '';
    }
    removeProperty(property) {
        if (!this._value) {
            return '';
        }
        const value = this._value[property];
        delete this._value[property];
        return value;
    }
    get cssText() {
        return this._cssText || '';
    }
    set cssText(cssText) {
        this._cssText = cssText;
    }
    toJSON() {
        const { _cssText, _value } = this;
        const hasCssText = _cssText !== null;
        const hasValue = _value !== null;
        if (hasCssText && hasValue) {
            return [_cssText, _value];
        }
fxy060608's avatar
fxy060608 已提交
338 339 340 341 342 343
        if (hasCssText) {
            return _cssText;
        }
        if (hasValue) {
            return _value;
        }
fxy060608's avatar
fxy060608 已提交
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
    }
}
const STYLE_PROPS = [
    '_value',
    '_cssText',
    'cssText',
    'getPropertyValue',
    'setProperty',
    'removeProperty',
    'toJSON',
];
function proxyStyle(uniCssStyle) {
    return new Proxy(uniCssStyle, {
        get(target, key, receiver) {
            if (STYLE_PROPS.indexOf(key) === -1) {
                return target.getPropertyValue(key);
            }
            return Reflect.get(target, key, receiver);
        },
        set(target, key, value, receiver) {
            if (STYLE_PROPS.indexOf(key) === -1) {
                target.setProperty(key, value);
                return true;
            }
            return Reflect.set(target, key, value, receiver);
        },
    });
}

fxy060608's avatar
fxy060608 已提交
373 374 375
const ATTR_MAP = {
    class: '.c',
    style: '.s',
fxy060608's avatar
fxy060608 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    onClick: '.e0',
    onChange: '.e1',
    onInput: '.e2',
    onLoad: '.e3',
    onError: '.e4',
    onTouchstart: '.e5',
    onTouchmove: '.e6',
    onTouchcancel: '.e7',
    onTouchend: '.e8',
    onLongpress: '.e9',
    onTransitionend: '.ea',
    onAnimationstart: '.eb',
    onAnimationiteration: '.ec',
    onAnimationend: '.ed',
    onTouchforcechange: '.ee',
fxy060608's avatar
fxy060608 已提交
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
};
function encodeAttr(name) {
    return ATTR_MAP[name] || name;
}
const COMPONENT_MAP = {
    VIEW: 1,
    IMAGE: 2,
    TEXT: 3,
    '#text': 4,
    '#comment': 5,
    NAVIGATOR: 6,
    FORM: 7,
    BUTTON: 8,
    INPUT: 9,
    LABEL: 10,
    RADIO: 11,
    CHECKBOX: 12,
    'CHECKBOX-GROUP': 13,
    AD: 14,
    AUDIO: 15,
    CAMERA: 16,
    CANVAS: 17,
    'COVER-IMAGE': 18,
    'COVER-VIEW': 19,
    EDITOR: 20,
    'FUNCTIONAL-PAGE-NAVIGATOR': 21,
    ICON: 22,
    'RADIO-GROUP': 23,
    'LIVE-PLAYER': 24,
    'LIVE-PUSHER': 25,
    MAP: 26,
    'MOVABLE-AREA': 27,
    'MOVABLE-VIEW': 28,
    'OFFICIAL-ACCOUNT': 29,
    'OPEN-DATA': 30,
    PICKER: 31,
    'PICKER-VIEW': 32,
    'PICKER-VIEW-COLUMN': 33,
    PROGRESS: 34,
    'RICH-TEXT': 35,
    'SCROLL-VIEW': 36,
    SLIDER: 37,
    SWIPER: 38,
    'SWIPER-ITEM': 39,
    SWITCH: 40,
    TEXTAREA: 41,
    VIDEO: 42,
    'WEB-VIEW': 43,
};
function encodeTag(tag) {
    return COMPONENT_MAP[tag] || tag;
}

fxy060608's avatar
fxy060608 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
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 已提交
463
    if (!node.nodeId && node.pageNode) {
fxy060608's avatar
fxy060608 已提交
464 465 466
        node.nodeId = node.pageNode.genId();
    }
}
fxy060608's avatar
fxy060608 已提交
467
// 为优化性能,各平台不使用proxy来实现node的操作拦截,而是直接通过pageNode定制
fxy060608's avatar
fxy060608 已提交
468
class UniNode extends UniEventTarget {
fxy060608's avatar
fxy060608 已提交
469
    constructor(nodeType, nodeName, container) {
fxy060608's avatar
fxy060608 已提交
470 471 472 473
        super();
        this.pageNode = null;
        this.parentNode = null;
        this._text = null;
fxy060608's avatar
fxy060608 已提交
474 475
        if (container) {
            const { pageNode } = container;
fxy060608's avatar
fxy060608 已提交
476 477 478 479 480
            if (pageNode) {
                this.pageNode = pageNode;
                this.nodeId = pageNode.genId();
                pageNode.onCreate(this, encodeTag(nodeName));
            }
fxy060608's avatar
fxy060608 已提交
481
        }
fxy060608's avatar
fxy060608 已提交
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
        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 已提交
497 498 499 500
    get nodeValue() {
        return null;
    }
    set nodeValue(_val) { }
fxy060608's avatar
fxy060608 已提交
501 502 503 504 505
    get textContent() {
        return this._text || '';
    }
    set textContent(text) {
        this._text = text;
fxy060608's avatar
fxy060608 已提交
506 507 508
        if (this.pageNode) {
            this.pageNode.onTextContent(this, text);
        }
fxy060608's avatar
fxy060608 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
    }
    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 = shared.extend(Object.create(Object.getPrototypeOf(this)), this);
        const { attributes } = cloned;
        if (attributes) {
            cloned.attributes = shared.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;
fxy060608's avatar
fxy060608 已提交
540
        let index;
fxy060608's avatar
fxy060608 已提交
541
        if (refChild) {
fxy060608's avatar
fxy060608 已提交
542
            index = childNodes.indexOf(refChild);
fxy060608's avatar
fxy060608 已提交
543 544 545
            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 已提交
546
            childNodes.splice(index, 0, newChild);
fxy060608's avatar
fxy060608 已提交
547 548
        }
        else {
fxy060608's avatar
fxy060608 已提交
549
            index = childNodes.length;
fxy060608's avatar
fxy060608 已提交
550 551
            childNodes.push(newChild);
        }
fxy060608's avatar
fxy060608 已提交
552 553 554
        return this.pageNode
            ? this.pageNode.onInsertBefore(this, newChild, index)
            : newChild;
fxy060608's avatar
fxy060608 已提交
555 556 557 558 559 560 561 562 563
    }
    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 已提交
564 565 566
        return this.pageNode
            ? this.pageNode.onRemoveChild(this, oldChild)
            : oldChild;
fxy060608's avatar
fxy060608 已提交
567 568 569
    }
}
class UniBaseNode extends UniNode {
fxy060608's avatar
fxy060608 已提交
570 571
    constructor(nodeType, nodeName, container) {
        super(nodeType, nodeName, container);
fxy060608's avatar
fxy060608 已提交
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
        this.attributes = Object.create(null);
        this._html = null;
        this.style = proxyStyle(new UniCSSStyleDeclaration());
    }
    get className() {
        return (this.attributes['class'] || '');
    }
    set className(val) {
        this.setAttribute('class', val);
    }
    get innerHTML() {
        return '';
    }
    set innerHTML(html) {
        this._html = html;
    }
    addEventListener(type, listener, options) {
        super.addEventListener(type, listener, options);
        const normalized = normalizeEventType(type);
        if (!this.attributes[normalized]) {
            this.setAttribute(normalized, 1);
        }
    }
    removeEventListener(type, callback, options) {
        super.removeEventListener(type, callback, options);
        const normalized = normalizeEventType(type);
fxy060608's avatar
fxy060608 已提交
598
        if (this.attributes[encodeAttr(normalized)]) {
fxy060608's avatar
fxy060608 已提交
599 600 601 602
            this.removeAttribute(normalized);
        }
    }
    getAttribute(qualifiedName) {
fxy060608's avatar
fxy060608 已提交
603
        return this.attributes[encodeAttr(qualifiedName)];
fxy060608's avatar
fxy060608 已提交
604 605
    }
    removeAttribute(qualifiedName) {
fxy060608's avatar
fxy060608 已提交
606
        qualifiedName = encodeAttr(qualifiedName);
fxy060608's avatar
fxy060608 已提交
607
        delete this.attributes[qualifiedName];
fxy060608's avatar
fxy060608 已提交
608 609 610
        if (this.pageNode) {
            this.pageNode.onRemoveAttribute(this, qualifiedName);
        }
fxy060608's avatar
fxy060608 已提交
611 612
    }
    setAttribute(qualifiedName, value) {
fxy060608's avatar
fxy060608 已提交
613
        qualifiedName = encodeAttr(qualifiedName);
fxy060608's avatar
fxy060608 已提交
614
        this.attributes[qualifiedName] = value;
fxy060608's avatar
fxy060608 已提交
615 616 617
        if (this.pageNode) {
            this.pageNode.onSetAttribute(this, qualifiedName, value);
        }
fxy060608's avatar
fxy060608 已提交
618
    }
fxy060608's avatar
fxy060608 已提交
619
    toJSON(opts = {}) {
fxy060608's avatar
fxy060608 已提交
620 621 622 623
        const res = {
            a: this.attributes,
            s: this.style.toJSON(),
        };
fxy060608's avatar
fxy060608 已提交
624 625 626 627
        if (!opts.attr) {
            res.i = this.nodeId;
            res.n = encodeTag(this.nodeName);
        }
fxy060608's avatar
fxy060608 已提交
628 629 630 631 632 633 634 635
        if (this._text !== null) {
            res.t = this._text;
        }
        return res;
    }
}

class UniCommentNode extends UniNode {
fxy060608's avatar
fxy060608 已提交
636 637
    constructor(text, container) {
        super(NODE_TYPE_COMMENT, '#comment', container);
fxy060608's avatar
fxy060608 已提交
638 639
        this._text = text;
    }
fxy060608's avatar
fxy060608 已提交
640 641 642 643 644 645 646 647
    toJSON(opts = {}) {
        return opts.attr
            ? { t: this._text }
            : {
                i: this.nodeId,
                t: this._text,
            };
    }
fxy060608's avatar
fxy060608 已提交
648 649 650
}

class UniElement extends UniBaseNode {
fxy060608's avatar
fxy060608 已提交
651 652
    constructor(nodeName, container) {
        super(NODE_TYPE_ELEMENT, nodeName.toUpperCase(), container);
fxy060608's avatar
fxy060608 已提交
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
        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 已提交
668 669
    constructor(text, container) {
        super(NODE_TYPE_TEXT, '#text', container);
fxy060608's avatar
fxy060608 已提交
670 671 672 673 674 675 676
        this._text = text;
    }
    get nodeValue() {
        return this._text || '';
    }
    set nodeValue(text) {
        this._text = text;
fxy060608's avatar
fxy060608 已提交
677 678 679
        if (this.pageNode) {
            this.pageNode.onNodeValue(this, text);
        }
fxy060608's avatar
fxy060608 已提交
680 681 682
    }
}

fxy060608's avatar
fxy060608 已提交
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
const DECODED_ATTR_MAP = /*#__PURE__*/ Object.keys(ATTR_MAP).reduce((map, name) => {
    map[ATTR_MAP[name]] = name;
    return map;
}, Object.create(null));
function decodeAttr(name) {
    return DECODED_ATTR_MAP[name] || name;
}
const DECODED_COMPONENT_ARR = /*#__PURE__*/ Object.keys(COMPONENT_MAP).reduce((arr, name) => {
    arr.push(name.toLowerCase());
    return arr;
}, ['']);
function decodeTag(tag) {
    return DECODED_COMPONENT_ARR[tag] || tag;
}

fxy060608's avatar
fxy060608 已提交
698
function cache(fn) {
fxy060608's avatar
fxy060608 已提交
699
    const cache = Object.create(null);
fxy060608's avatar
fxy060608 已提交
700
    return (str) => {
fxy060608's avatar
fxy060608 已提交
701 702
        const hit = cache[str];
        return hit || (cache[str] = fn(str));
fxy060608's avatar
fxy060608 已提交
703 704 705 706 707
    };
}
function cacheStringFunction(fn) {
    return cache(fn);
}
fxy060608's avatar
fxy060608 已提交
708 709
function getLen(str = '') {
    return ('' + str).replace(/[^\x00-\xff]/g, '**').length;
fxy060608's avatar
fxy060608 已提交
710 711 712
}
function removeLeadingSlash(str) {
    return str.indexOf('/') === 0 ? str.substr(1) : str;
fxy060608's avatar
fxy060608 已提交
713 714 715 716 717 718 719
}
const invokeArrayFns = (fns, arg) => {
    let ret;
    for (let i = 0; i < fns.length; i++) {
        ret = fns[i](arg);
    }
    return ret;
fxy060608's avatar
fxy060608 已提交
720 721 722 723 724
};
function updateElementStyle(element, styles) {
    for (const attrName in styles) {
        element.style[attrName] = styles[attrName];
    }
fxy060608's avatar
fxy060608 已提交
725 726 727
}
function once(fn, ctx = null) {
    let res;
fxy060608's avatar
fxy060608 已提交
728
    return ((...args) => {
fxy060608's avatar
fxy060608 已提交
729 730 731 732 733
        if (fn) {
            res = fn.apply(ctx, args);
            fn = null;
        }
        return res;
fxy060608's avatar
fxy060608 已提交
734
    });
fxy060608's avatar
fxy060608 已提交
735
}
D
DCloud_LXH 已提交
736 737 738 739 740 741 742 743 744 745 746 747 748
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 已提交
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
}
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);
    }
D
DCloud_LXH 已提交
770
}
fxy060608's avatar
fxy060608 已提交
771

fxy060608's avatar
fxy060608 已提交
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
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 (shared.isPlainObject(val)) {
                val = JSON.stringify(val);
            }
            return encodeStr(key) + '=' + encodeStr(val);
        })
            .filter((x) => x.length > 0)
            .join('&')
        : null;
    return res ? `?${res}` : '';
fxy060608's avatar
fxy060608 已提交
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
}
/**
 * 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];
fxy060608's avatar
fxy060608 已提交
843
            if (!shared.isArray(currentValue)) {
fxy060608's avatar
fxy060608 已提交
844 845 846 847 848 849 850 851 852
                currentValue = query[key] = [currentValue];
            }
            currentValue.push(value);
        }
        else {
            query[key] = value;
        }
    }
    return query;
fxy060608's avatar
fxy060608 已提交
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
}

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;
}

const NAVBAR_HEIGHT = 44;
const TABBAR_HEIGHT = 50;
fxy060608's avatar
fxy060608 已提交
870
const ON_REACH_BOTTOM_DISTANCE = 50;
fxy060608's avatar
fxy060608 已提交
871 872
const RESPONSIVE_MIN_WIDTH = 768;
const COMPONENT_NAME_PREFIX = 'VUni';
fxy060608's avatar
fxy060608 已提交
873
const PRIMARY_COLOR = '#007aff';
fxy060608's avatar
fxy060608 已提交
874 875
const SELECTED_COLOR = '#0062cc'; // 选中的颜色,如选项卡默认的选中颜色
const BACKGROUND_COLOR = '#f7f7f7'; // 背景色,如标题栏默认背景色
fxy060608's avatar
fxy060608 已提交
876
const UNI_SSR = '__uniSSR';
fxy060608's avatar
fxy060608 已提交
877
const UNI_SSR_TITLE = 'title';
fxy060608's avatar
fxy060608 已提交
878
const UNI_SSR_STORE = 'store';
fxy060608's avatar
fxy060608 已提交
879
const UNI_SSR_DATA = 'data';
fxy060608's avatar
fxy060608 已提交
880 881 882 883
const UNI_SSR_GLOBAL_DATA = 'globalData';
const SCHEME_RE = /^([a-z-]+:)?\/\//i;
const DATA_RE = /^data:.*,.*/;
const WEB_INVOKE_APPSERVICE = 'WEB_INVOKE_APPSERVICE';
fxy060608's avatar
fxy060608 已提交
884

fxy060608's avatar
fxy060608 已提交
885 886 887 888 889 890
function getEnvLocale() {
    const { env } = process;
    const lang = env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE;
    return (lang && lang.replace(/[.:].*/, '')) || 'en';
}

fxy060608's avatar
fxy060608 已提交
891
exports.BACKGROUND_COLOR = BACKGROUND_COLOR;
fxy060608's avatar
fxy060608 已提交
892 893 894
exports.BUILT_IN_TAGS = BUILT_IN_TAGS;
exports.COMPONENT_NAME_PREFIX = COMPONENT_NAME_PREFIX;
exports.COMPONENT_PREFIX = COMPONENT_PREFIX;
fxy060608's avatar
fxy060608 已提交
895
exports.COMPONENT_SELECTOR_PREFIX = COMPONENT_SELECTOR_PREFIX;
fxy060608's avatar
fxy060608 已提交
896
exports.DATA_RE = DATA_RE;
fxy060608's avatar
fxy060608 已提交
897
exports.NAVBAR_HEIGHT = NAVBAR_HEIGHT;
fxy060608's avatar
fxy060608 已提交
898 899 900 901
exports.NODE_TYPE_COMMENT = NODE_TYPE_COMMENT;
exports.NODE_TYPE_ELEMENT = NODE_TYPE_ELEMENT;
exports.NODE_TYPE_PAGE = NODE_TYPE_PAGE;
exports.NODE_TYPE_TEXT = NODE_TYPE_TEXT;
fxy060608's avatar
fxy060608 已提交
902
exports.ON_REACH_BOTTOM_DISTANCE = ON_REACH_BOTTOM_DISTANCE;
fxy060608's avatar
fxy060608 已提交
903
exports.PLUS_RE = PLUS_RE;
fxy060608's avatar
fxy060608 已提交
904
exports.PRIMARY_COLOR = PRIMARY_COLOR;
fxy060608's avatar
fxy060608 已提交
905
exports.RESPONSIVE_MIN_WIDTH = RESPONSIVE_MIN_WIDTH;
fxy060608's avatar
fxy060608 已提交
906
exports.SCHEME_RE = SCHEME_RE;
fxy060608's avatar
fxy060608 已提交
907
exports.SELECTED_COLOR = SELECTED_COLOR;
fxy060608's avatar
fxy060608 已提交
908 909
exports.TABBAR_HEIGHT = TABBAR_HEIGHT;
exports.TAGS = TAGS;
fxy060608's avatar
fxy060608 已提交
910 911 912
exports.UNI_SSR = UNI_SSR;
exports.UNI_SSR_DATA = UNI_SSR_DATA;
exports.UNI_SSR_GLOBAL_DATA = UNI_SSR_GLOBAL_DATA;
fxy060608's avatar
fxy060608 已提交
913
exports.UNI_SSR_STORE = UNI_SSR_STORE;
fxy060608's avatar
fxy060608 已提交
914
exports.UNI_SSR_TITLE = UNI_SSR_TITLE;
fxy060608's avatar
fxy060608 已提交
915 916 917 918 919 920 921 922
exports.UniBaseNode = UniBaseNode;
exports.UniCommentNode = UniCommentNode;
exports.UniElement = UniElement;
exports.UniEvent = UniEvent;
exports.UniInputElement = UniInputElement;
exports.UniNode = UniNode;
exports.UniTextAreaElement = UniTextAreaElement;
exports.UniTextNode = UniTextNode;
fxy060608's avatar
fxy060608 已提交
923
exports.WEB_INVOKE_APPSERVICE = WEB_INVOKE_APPSERVICE;
fxy060608's avatar
fxy060608 已提交
924
exports.addFont = addFont;
fxy060608's avatar
fxy060608 已提交
925
exports.cache = cache;
fxy060608's avatar
fxy060608 已提交
926
exports.cacheStringFunction = cacheStringFunction;
Q
qiang 已提交
927
exports.callOptions = callOptions;
fxy060608's avatar
fxy060608 已提交
928
exports.createRpx2Unit = createRpx2Unit;
fxy060608's avatar
fxy060608 已提交
929
exports.debounce = debounce;
fxy060608's avatar
fxy060608 已提交
930
exports.decode = decode;
fxy060608's avatar
fxy060608 已提交
931 932
exports.decodeAttr = decodeAttr;
exports.decodeTag = decodeTag;
fxy060608's avatar
fxy060608 已提交
933
exports.decodedQuery = decodedQuery;
fxy060608's avatar
fxy060608 已提交
934
exports.defaultRpx2Unit = defaultRpx2Unit;
fxy060608's avatar
fxy060608 已提交
935 936
exports.encodeAttr = encodeAttr;
exports.encodeTag = encodeTag;
D
DCloud_LXH 已提交
937
exports.formatDateTime = formatDateTime;
Q
qiang 已提交
938
exports.getCustomDataset = getCustomDataset;
fxy060608's avatar
fxy060608 已提交
939
exports.getEnvLocale = getEnvLocale;
fxy060608's avatar
fxy060608 已提交
940
exports.getLen = getLen;
Q
qiang 已提交
941
exports.initCustomDataset = initCustomDataset;
fxy060608's avatar
fxy060608 已提交
942
exports.invokeArrayFns = invokeArrayFns;
fxy060608's avatar
fxy060608 已提交
943 944 945
exports.isBuiltInComponent = isBuiltInComponent;
exports.isCustomElement = isCustomElement;
exports.isNativeTag = isNativeTag;
fxy060608's avatar
fxy060608 已提交
946 947
exports.isServiceCustomElement = isServiceCustomElement;
exports.isServiceNativeTag = isServiceNativeTag;
fxy060608's avatar
fxy060608 已提交
948
exports.normalizeDataset = normalizeDataset;
fxy060608's avatar
fxy060608 已提交
949
exports.normalizeTarget = normalizeTarget;
fxy060608's avatar
fxy060608 已提交
950
exports.once = once;
fxy060608's avatar
fxy060608 已提交
951
exports.parseQuery = parseQuery;
fxy060608's avatar
fxy060608 已提交
952
exports.passive = passive;
fxy060608's avatar
fxy060608 已提交
953
exports.plusReady = plusReady;
fxy060608's avatar
fxy060608 已提交
954
exports.removeLeadingSlash = removeLeadingSlash;
fxy060608's avatar
fxy060608 已提交
955
exports.sanitise = sanitise;
fxy060608's avatar
fxy060608 已提交
956
exports.scrollTo = scrollTo;
fxy060608's avatar
fxy060608 已提交
957
exports.stringifyQuery = stringifyQuery;
fxy060608's avatar
fxy060608 已提交
958
exports.updateElementStyle = updateElementStyle;