uni-shared.cjs.js 11.1 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');

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
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) {
    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 已提交
28 29 30 31 32 33
function passive(passive) {
    return { passive };
}
function normalizeDataset(el) {
    // TODO
    return JSON.parse(JSON.stringify(el.dataset || {}));
fxy060608's avatar
fxy060608 已提交
34 35 36 37 38 39 40 41 42
}
function normalizeTarget(el) {
    const { id, offsetTop, offsetLeft } = el;
    return {
        id,
        dataset: normalizeDataset(el),
        offsetTop,
        offsetLeft,
    };
fxy060608's avatar
fxy060608 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55
}
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) {
56
            const { style, weight, stretch, unicodeRange, variant, featureSettings } = desc;
fxy060608's avatar
fxy060608 已提交
57 58 59 60 61 62 63 64 65 66 67
            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 已提交
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
}
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 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114
}

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 已提交
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
    '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 已提交
157
const TAGS = [
fxy060608's avatar
fxy060608 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    '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 已提交
177 178 179 180 181 182 183 184 185
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 已提交
186 187
const COMPONENT_SELECTOR_PREFIX = 'uni-';
const COMPONENT_PREFIX = 'v-' + COMPONENT_SELECTOR_PREFIX;
fxy060608's avatar
fxy060608 已提交
188

fxy060608's avatar
fxy060608 已提交
189 190
function getLen(str = '') {
    return ('' + str).replace(/[^\x00-\xff]/g, '**').length;
fxy060608's avatar
fxy060608 已提交
191 192 193
}
function removeLeadingSlash(str) {
    return str.indexOf('/') === 0 ? str.substr(1) : str;
fxy060608's avatar
fxy060608 已提交
194 195 196 197 198 199 200
}
const invokeArrayFns = (fns, arg) => {
    let ret;
    for (let i = 0; i < fns.length; i++) {
        ret = fns[i](arg);
    }
    return ret;
fxy060608's avatar
fxy060608 已提交
201 202 203 204 205
};
function updateElementStyle(element, styles) {
    for (const attrName in styles) {
        element.style[attrName] = styles[attrName];
    }
fxy060608's avatar
fxy060608 已提交
206 207 208
}
function once(fn, ctx = null) {
    let res;
fxy060608's avatar
fxy060608 已提交
209
    return ((...args) => {
fxy060608's avatar
fxy060608 已提交
210 211 212 213 214
        if (fn) {
            res = fn.apply(ctx, args);
            fn = null;
        }
        return res;
fxy060608's avatar
fxy060608 已提交
215
    });
fxy060608's avatar
fxy060608 已提交
216
}
D
DCloud_LXH 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230
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()));
    }
}
fxy060608's avatar
fxy060608 已提交
231

fxy060608's avatar
fxy060608 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
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 已提交
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
}
/**
 * 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 已提交
303
            if (!shared.isArray(currentValue)) {
fxy060608's avatar
fxy060608 已提交
304 305 306 307 308 309 310 311 312
                currentValue = query[key] = [currentValue];
            }
            currentValue.push(value);
        }
        else {
            query[key] = value;
        }
    }
    return query;
fxy060608's avatar
fxy060608 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
}

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 已提交
330
const ON_REACH_BOTTOM_DISTANCE = 50;
fxy060608's avatar
fxy060608 已提交
331 332
const RESPONSIVE_MIN_WIDTH = 768;
const COMPONENT_NAME_PREFIX = 'VUni';
fxy060608's avatar
fxy060608 已提交
333 334
const PRIMARY_COLOR = '#007aff';
const UNI_SSR = '__uniSSR';
fxy060608's avatar
fxy060608 已提交
335
const UNI_SSR_STORE = 'store';
fxy060608's avatar
fxy060608 已提交
336 337
const UNI_SSR_DATA = 'data';
const UNI_SSR_GLOBAL_DATA = 'globalData';
fxy060608's avatar
fxy060608 已提交
338

fxy060608's avatar
fxy060608 已提交
339 340 341 342 343 344
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 已提交
345 346 347
exports.BUILT_IN_TAGS = BUILT_IN_TAGS;
exports.COMPONENT_NAME_PREFIX = COMPONENT_NAME_PREFIX;
exports.COMPONENT_PREFIX = COMPONENT_PREFIX;
fxy060608's avatar
fxy060608 已提交
348
exports.COMPONENT_SELECTOR_PREFIX = COMPONENT_SELECTOR_PREFIX;
fxy060608's avatar
fxy060608 已提交
349
exports.NAVBAR_HEIGHT = NAVBAR_HEIGHT;
fxy060608's avatar
fxy060608 已提交
350
exports.ON_REACH_BOTTOM_DISTANCE = ON_REACH_BOTTOM_DISTANCE;
fxy060608's avatar
fxy060608 已提交
351
exports.PLUS_RE = PLUS_RE;
fxy060608's avatar
fxy060608 已提交
352
exports.PRIMARY_COLOR = PRIMARY_COLOR;
fxy060608's avatar
fxy060608 已提交
353
exports.RESPONSIVE_MIN_WIDTH = RESPONSIVE_MIN_WIDTH;
fxy060608's avatar
fxy060608 已提交
354 355
exports.TABBAR_HEIGHT = TABBAR_HEIGHT;
exports.TAGS = TAGS;
fxy060608's avatar
fxy060608 已提交
356 357 358
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 已提交
359
exports.UNI_SSR_STORE = UNI_SSR_STORE;
fxy060608's avatar
fxy060608 已提交
360
exports.addFont = addFont;
fxy060608's avatar
fxy060608 已提交
361
exports.createRpx2Unit = createRpx2Unit;
fxy060608's avatar
fxy060608 已提交
362
exports.debounce = debounce;
fxy060608's avatar
fxy060608 已提交
363 364
exports.decode = decode;
exports.decodedQuery = decodedQuery;
fxy060608's avatar
fxy060608 已提交
365
exports.defaultRpx2Unit = defaultRpx2Unit;
D
DCloud_LXH 已提交
366
exports.formatDateTime = formatDateTime;
fxy060608's avatar
fxy060608 已提交
367
exports.getEnvLocale = getEnvLocale;
fxy060608's avatar
fxy060608 已提交
368
exports.getLen = getLen;
fxy060608's avatar
fxy060608 已提交
369
exports.invokeArrayFns = invokeArrayFns;
fxy060608's avatar
fxy060608 已提交
370 371 372
exports.isBuiltInComponent = isBuiltInComponent;
exports.isCustomElement = isCustomElement;
exports.isNativeTag = isNativeTag;
fxy060608's avatar
fxy060608 已提交
373
exports.normalizeDataset = normalizeDataset;
fxy060608's avatar
fxy060608 已提交
374
exports.normalizeTarget = normalizeTarget;
fxy060608's avatar
fxy060608 已提交
375
exports.once = once;
fxy060608's avatar
fxy060608 已提交
376
exports.parseQuery = parseQuery;
fxy060608's avatar
fxy060608 已提交
377
exports.passive = passive;
fxy060608's avatar
fxy060608 已提交
378
exports.plusReady = plusReady;
fxy060608's avatar
fxy060608 已提交
379
exports.removeLeadingSlash = removeLeadingSlash;
fxy060608's avatar
fxy060608 已提交
380
exports.sanitise = sanitise;
fxy060608's avatar
fxy060608 已提交
381
exports.scrollTo = scrollTo;
fxy060608's avatar
fxy060608 已提交
382
exports.stringifyQuery = stringifyQuery;
fxy060608's avatar
fxy060608 已提交
383
exports.updateElementStyle = updateElementStyle;