UNPKG

magic-img

Version:

让你的图片加载更加优雅

588 lines (587 loc) 24.8 kB
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function() { var self = this, args = arguments; return new Promise(function(resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function() {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [ null ]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _defineProperties(target, props) { for(var i = 0; i < props.length; i++){ var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var _typeof = function(obj) { "@swc/helpers - typeof"; return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; }; function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})); return true; } catch (e) { return false; } } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } var __generator = this && this.__generator || function(thisArg, body) { var f, y, t, g, _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }; return(g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g); function verb(n) { return function(v) { return step([ n, v ]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while(_)try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [ op[0] & 2, t.value ]; switch(op[0]){ case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [ 0 ]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [ 6, e ]; y = 0; } finally{ f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __defNormalProp = function(obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; }; var __export = function(target, all) { for(var name in all)__defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = function(to, from, except, desc) { if (from && typeof from === "object" || typeof from === "function") { var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined; try { var _loop = function() { var key = _step.value; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: function() { return from[key]; }, enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); }; for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop(); } catch (err) { _didIteratorError = true; _iteratorError = err; } finally{ try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally{ if (_didIteratorError) { throw _iteratorError; } } } } return to; }; var __toCommonJS = function(mod) { return __copyProps(__defProp({}, "__esModule", { value: true }), mod); }; var __publicField = function(obj, key, value) { __defNormalProp(obj, (typeof key === "undefined" ? "undefined" : _typeof(key)) !== "symbol" ? key + "" : key, value); return value; }; // src/index.ts var src_exports = {}; __export(src_exports, { default: function() { return src_default; } }); module.exports = __toCommonJS(src_exports); // src/magic.ts var wait = function() { var time = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 0; return new Promise(function(r) { return setTimeout(r, time); }); }; var imgPlaceholder = [ "lqip", "blurhash" ]; function install() { try { var MagicImg = /*#__PURE__*/ function(HTMLElement1) { "use strict"; _inherits(MagicImg, HTMLElement1); var _super = _createSuper(MagicImg); function MagicImg() { _classCallCheck(this, MagicImg); var _this; _this = _super.call(this); __publicField(_assertThisInitialized(_this), "initial", false); __publicField(_assertThisInitialized(_this), "width", 0); __publicField(_assertThisInitialized(_this), "height", 0); __publicField(_assertThisInitialized(_this), "src", ""); __publicField(_assertThisInitialized(_this), "content", ""); __publicField(_assertThisInitialized(_this), "svg"); __publicField(_assertThisInitialized(_this), "img"); __publicField(_assertThisInitialized(_this), "smallImg"); _this.svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); _this.svg.setAttribute("preserveAspectRatio", "none"); _this.img = new Image(); _this.smallImg = new Image(); _this.svg.classList.add("magic-placeholder"); _this.smallImg.classList.add("magic-placeholder"); _this.img.classList.add("magic-target"); return _this; } _createClass(MagicImg, [ { key: "data", get: function get() { try { var src = this.getAttribute("src") || this.src; return JSON.parse(src); } catch (e) { console.log("src attribute error", e); return {}; } } }, { key: "connectedCallback", value: function connectedCallback() { var _this = this; return _asyncToGenerator(function() { var intersection; return __generator(this, function(_state) { _this.initial = true; if (!_this.getAttribute("src") && !_this.src) throw new Error("<magic-img /> src attribute is required,see:https://github.com/lishaobos/magic-img#%E4%BD%BF%E7%94%A8"); _this.setPlaceholder(); _this.appendChild(_this.img); intersection = new IntersectionObserver(function() { var _ref = _asyncToGenerator(function(entrys) { var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, isIntersecting, err; return __generator(this, function(_state) { switch(_state.label){ case 0: _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined; _state.label = 1; case 1: _state.trys.push([ 1, 6, 7, 8 ]); _iterator = entrys[Symbol.iterator](); _state.label = 2; case 2: if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [ 3, 5 ]; isIntersecting = _step.value.isIntersecting; if (!isIntersecting) return [ 3, 4 ]; return [ 4, _this.start() ]; case 3: _state.sent(); intersection.unobserve(_this); intersection.disconnect(); _state.label = 4; case 4: _iteratorNormalCompletion = true; return [ 3, 2 ]; case 5: return [ 3, 8 ]; case 6: err = _state.sent(); _didIteratorError = true; _iteratorError = err; return [ 3, 8 ]; case 7: try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally{ if (_didIteratorError) { throw _iteratorError; } } return [ 7 ]; case 8: return [ 2 ]; } }); }); return function(entrys) { return _ref.apply(this, arguments); }; }()); intersection.observe(_this); return [ 2 ]; }); })(); } }, { key: "setPlaceholder", value: function setPlaceholder() { var data = this.data; this.setAttribute("magic", data.magic); this.img.removeAttribute("status"); if (imgPlaceholder.includes(data.magic)) { this.smallImg.src = data.content; this.smallImg.setAttribute("width", data.width); this.smallImg.setAttribute("height", data.height); this.svg.parentNode && this.svg.parentNode.removeChild(this.svg); this.appendChild(this.smallImg); } else { this.svg.setAttribute("width", data.width); this.svg.setAttribute("height", data.height); this.svg.setAttribute("viewBox", "0 0 ".concat(data.width_ || data.width, " ").concat(data.height_ || data.height)); this.svg.innerHTML = data.content; this.smallImg.parentNode && this.smallImg.parentNode.removeChild(this.smallImg); this.appendChild(this.svg); } } }, { key: "start", value: function start() { var _this = this; return _asyncToGenerator(function() { var data; return __generator(this, function(_state) { data = _this.data; requestAnimationFrame(function() { _this.svg.setAttribute("status", "from"); _this.smallImg.setAttribute("status", "from"); _this.img.setAttribute("status", "from"); var start = performance.now(); _this.img.onload = function() { var to = function(isPrecive) { return requestAnimationFrame(function() { var status = isPrecive ? "to" : "noPrevice"; _this.svg.setAttribute("status", status); _this.smallImg.setAttribute("status", status); _this.img.setAttribute("status", status); }); }; to(performance.now() - start > 100); }; _this.img.src = data.src; }); return [ 2 ]; }); })(); } }, { key: "attributeChangedCallback", value: function attributeChangedCallback() { var _this = this; return _asyncToGenerator(function() { return __generator(this, function(_state) { switch(_state.label){ case 0: if (!_this.initial) return [ 2 ]; _this.setPlaceholder(); return [ 4, wait() ]; case 1: _state.sent(); return [ 4, _this.start() ]; case 2: _state.sent(); return [ 2 ]; } }); })(); } } ], [ { key: "observedAttributes", get: function get() { return [ "src" ]; } } ]); return MagicImg; }(_wrapNativeSuper(HTMLElement)); customElements.define("magic-img", MagicImg); } catch (e) {} } // src/index.ts var src_default = install; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = {});