react-micro-lifecycles
Version:
Micro life-cycles form React DOM nodes
98 lines (68 loc) • 2.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var sym = (typeof Symbol === 'undefined' ? 'undefined' : _typeof(Symbol)) === 'object' ? Symbol('mcycles') : '@@mcycles';
var noop = function noop() {};
var microLifecycles = function microLifecycles(props) {
var $attach = props.$attach;
var $update = props.$update;
var $detach = props.$detach;
var ref = props.ref;
var rest = props;
if (process.env.NODE_ENV !== 'production') {
rest = Object.assign({}, props);
}
delete rest.$attach;
delete rest.$update;
delete rest.$detach;
if (!$attach && !$update && !$detach) return props;
rest.ref = function (el) {
if (process.env.NODE_ENV !== 'production') {
if (ref && typeof ref !== 'function') {
console.error('react-micro-lifecycles received props with ref, expected ref to be a function, "' + (typeof ref === 'undefined' ? 'undefined' : _typeof(ref)) + '" provided.');
}
}
if (ref) ref(el);
if (!el) return;
if (!el[sym]) {
el[sym] = props;
var observer = new MutationObserver(function (mutations) {
for (var i = 0; i < mutations.length; i++) {
var mutation = mutations[i];
if (mutation.removedNodes.length) {
var nodes = mutation.removedNodes;
for (var j = 0; j < nodes.length; j++) {
if (nodes[j] === el) {
observer.disconnect();
var _oldProps = el[sym];
(_oldProps.$detach || noop)(el, _oldProps);
return;
}
}
}
}
});
observer.observe(el.parentNode, { childList: true });
($attach || noop)(el, props);
return;
}
var oldProps = el[sym];
el[sym] = props;
($update || noop)(el, props, oldProps);
};
return rest;
};
var createHyperscriptUnstable = function createHyperscriptUnstable(h) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var type = args[0];
if (typeof type !== 'string') return h.apply(undefined, args);
args[1] = microLifecycles(args[1] || {});
return h.apply(undefined, args);
};
};
exports.default = createHyperscriptUnstable;