UNPKG

@group_wtf_npm/loading

Version:

loading加载

110 lines (101 loc) 2.96 kB
/** * GlobalLoading 类 * 继承自 WtfLoading,并扩展了全局加载管理的功能。 */ class GlobalLoading { root = document.body // 挂载根元素 record = new Map(); // 用于记录加载实例 tag = null opts = { absolute: true, mask: 1 } constructor(opts) { Object.assign(this.opts, opts); this.init(); } /** * 初始化实例 */ init = () => { const { root, tag } = this.opts || {}; if (root) { const is_str = typeof root === 'string'; this.root = is_str ? document.querySelector(root) : root; } this.tag = typeof tag === 'string' ? document.createElement(tag) : tag; } /** * 显示加载动画 * @param {string} msg - 加载提示信息 * @param {string} [id] - 可选的加载 ID * @returns {string} 返回加载的唯一 ID */ show = (msg = '加载中', id, userOpts) => { const load_id = id ?? this.getId(6); this.record.set(load_id, msg); const opts = Object.assign({}, this.opts, userOpts); const { absolute, mask } = opts || {}; this.tag.setAttribute('absolute', absolute); this.tag.setAttribute('data-id', load_id); this.tag.setAttribute('mask', mask); this.tag.innerHTML = msg; if (!this.tag.isConnected) { this.root.appendChild(this.tag); } return load_id; } /** * 隐藏指定的加载动画 * @param {string} id - 加载的唯一 ID */ hide = id => { if (!id) return new Error('has`t_loading_id'); const res = this.record.delete(id); if (!res) return new Error(`hide_loading_fail: ${id}`); const next = [...this.record.entries()].shift(); if (!next) { if (!this.tag.isConnected) return; this.root.removeChild(this.tag); } else { const [lastId, lastMsg] = next; this.tag.innerHTML = lastMsg; this.tag.setAttribute('data-id', lastId); } } /** * 清除所有加载动画 */ clear = () => { this.record.clear(); if (!this.tag.isConnected) return; this.root.removeChild(this.tag); } /** * 暂停加载动画(从 DOM 中移除) */ pause = () => { if (!this.tag.isConnected) return; this.root.removeChild(this.tag); } /** * 恢复加载动画(重新添加到 DOM 中) */ resume = () => { if (this.tag.isConnected) return; this.root.appendChild(this.tag); } /** * 生成唯一 ID * @param {number} num - ID 的长度 * @returns {string} 返回生成的唯一 ID */ getId = (num = 6) => { const str = Math.random().toString(36); return [str.slice(-num), Date.now()].join('_'); } } export { GlobalLoading, GlobalLoading as default }