UNPKG

@livelybone/copy

Version:

About clipboard copy, Object simple&deep copy

304 lines (288 loc) 10.4 kB
/** * Bundle of @livelybone/copy * Generated: 2023-07-25 * Version: 2.6.6 * License: MIT * Author: 2631541504@qq.com */ /** * @param {Element} dom * @param {Object} options - Optional * @returns {Boolean} * */ function copyDom(dom, options) { var defaultObj = { clearSelect: false, cut: false }; var opts = Object.assign({}, defaultObj, options); var clearSelect = opts.clearSelect, cut = opts.cut; var range; var selection; if (window.getSelection) { selection = window.getSelection(); if (!selection) { console.error("copyDom: window.getSelection() return null"); return false; } range = window.document.createRange(); selection.removeAllRanges(); range.selectNode(dom); selection.addRange(range); } else { // @ts-ignore var createTextRange = document.body.createTextRange; /* IE < 9 */ if (createTextRange) { range = createTextRange(); range.moveToElementText(dom); range.select(); } } /* use document.execCommand `copy` */ var success = document.execCommand('copy'); if (selection && clearSelect) selection.removeAllRanges(); if (cut) { if (dom instanceof HTMLInputElement || dom instanceof HTMLTextAreaElement) { dom.value = ''; } else dom.innerHTML = ''; } return success; } /** * @param {String} text * @return {Promise<boolean>} * */ function copyText(text) { return new Promise(function (res, rej) { if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text).then(function () { return res(true); }).catch(function (e) { var err = new Error(e.message ? "copyText failed, reason: ".concat(e.message) : 'copyText failed'); rej(err); }); } else { var textEl = document.createElement('span'); textEl.style.position = 'fixed'; textEl.style.left = '0'; textEl.style.top = '0'; textEl.style.zIndex = '-999'; textEl.innerText = text; document.body.appendChild(textEl); var bool = copyDom(textEl); document.body.removeChild(textEl); if (bool) res(bool);else rej(new Error('copyText failed')); } }); } function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } /** * @description If param obj is expected that can be copied * */ var ExpectedObjType = /*#__PURE__*/function (ExpectedObjType) { ExpectedObjType["NormalObj"] = "object"; ExpectedObjType["Array"] = "Array"; return ExpectedObjType; }({}); function expectedObjType(obj) { var unexpectedObjConstructors = [typeof Promise !== 'undefined' && Promise, typeof Date !== 'undefined' && Date, typeof Error !== 'undefined' && Error, typeof RegExp !== 'undefined' && RegExp, typeof FileList !== 'undefined' && FileList, typeof File !== 'undefined' && File, typeof Element !== 'undefined' && Element, typeof Window !== 'undefined' && Window, typeof Document !== 'undefined' && Document]; return _typeof(obj) === 'object' && !(obj === null || unexpectedObjConstructors.some(function (it) { return it && obj instanceof it; })) ? obj instanceof Array ? ExpectedObjType.Array : ExpectedObjType.NormalObj : false; } function newObj(target) { return target instanceof Array ? [] : {}; } /** * @description Returns the start dimension of the nested loop * @param {Object} obj * @param {Array} tParents - Target parents * */ function circularStructureIndex(obj, tParents) { var index = Object.keys(tParents).find(function (i) { return tParents[+i] === obj; }); return index !== undefined ? { index: +index } : undefined; } /** * @description Returns the start dimension of the nested loop * */ function isCircularStructure(obj) { var paths = ['', '']; var isCircular = function isCircular(object) { var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['Object']; var oParents = arguments.length > 2 ? arguments[2] : undefined; if (_typeof(object) !== 'object' || object === null) return false; var parents = oParents ? [].concat(_toConsumableArray(oParents), [object]) : [object]; return Object.entries(object).some(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], value = _ref2[1]; var cPath = [].concat(_toConsumableArray(path), [key]); var circularIndex = circularStructureIndex(value, parents); if (circularIndex) { paths[0] = cPath.slice(0, circularIndex.index + 1).reduce(function (pre, p) { return "".concat(pre, ".").concat(p); }, '').replace(/^\./, ''); paths[1] = cPath.reduce(function (pre, p) { return "".concat(pre, ".").concat(p); }, '').replace(/^\./, ''); return true; } return isCircular(value, cPath, parents); }); }; return isCircular(obj) ? paths : null; } /** * @description Deep copy, deal nested loop * @param target * @param {Array} tParents - Target parents * @param {Array} tCurParents - Current result parents * */ function copyFn(target, tParents, tCurParents) { if (expectedObjType(target)) { var result = newObj(target); var parents = tParents ? [].concat(_toConsumableArray(tParents), [target]) : [target]; var curParents = tCurParents ? [].concat(_toConsumableArray(tCurParents), [result]) : [result]; Object.keys(target).forEach(function (key) { var isCircular = circularStructureIndex(target[key], parents); if (isCircular) { result[key] = curParents[isCircular.index]; } else { result[key] = copyFn(target[key], parents, curParents); } }); return result; } return target; } /** * @description Deep copy, has the ability to deal nested loop * */ function objectDeepCopy(obj) { return copyFn(obj); } /** * @description Deep copy, cannot deal nested loop * */ function objectSimpleCopy(obj) { return JSON.parse(JSON.stringify(obj)); } function merge(target) { for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { rest[_key - 1] = arguments[_key]; } rest.forEach(function (obj) { Object.entries(obj).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], val = _ref2[1]; if (key === '__proto__' || key === 'constructor' || key === 'prototype') { return target; } var obj1 = target[key]; if (expectedObjType(val) && expectedObjType(obj1)) { merge(obj1, val); } else { target[key] = _typeof(val) === 'object' ? objectSimpleCopy(val) : val; } }); }); return target; } /** * @description Deep merge, cannot deal nested loop * @return The first parameter object which has been merged * */ function objectDeepMerge(target) { var allTypeIs = 'same'; for (var _len2 = arguments.length, rest = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { rest[_key2 - 1] = arguments[_key2]; } var args = [target].concat(rest); args.forEach(function (obj, i) { var paths = isCircularStructure(obj); if (paths) { var pathsStr = JSON.stringify(paths); throw new Error("objectDeepMerge: Circular structure is not supported, the ".concat(i, "th parameter is a circular structure with CircularStructurePaths(").concat(pathsStr, ")")); } var type = expectedObjType(obj); if (!type || allTypeIs !== 'same' && allTypeIs !== type) { throw new Error('objectDeepMerge: Please ensure that parameters are all Array or normal Object'); } else allTypeIs = type; }); return merge.apply(void 0, [target].concat(rest)); } export { copyDom, copyText, isCircularStructure, objectDeepCopy, objectDeepMerge, objectSimpleCopy };