react-any-attr
Version:
Enables you to create any HTML attribute in React spearing the headache.
85 lines (84 loc) • 3.36 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));
exports.asObject = function (anything) {
return function _asObjectOrAsStringClosure(node, property) {
// @ts-ignore
node[property] = anything;
};
};
exports.asString = function (anything) {
return function _asObjectOrAsStringClosure(node, property) {
var anyValue = anything;
if (anyValue instanceof Function) {
node.setAttribute(property, anything);
return;
}
if (anyValue instanceof Object) {
try {
anyValue = JSON.stringify(anything);
}
catch (_a) {
anyValue = anything;
}
}
node.setAttribute(property, anyValue);
};
};
var AnyAttribute = function (props) {
var children = props.children, attributes = props.attributes;
var nodes = [];
var arrChildren = [].concat(children);
var afterRefs = function (isLast) {
if (isLast) {
nodes.forEach(function (node) {
var properties = Object.keys(attributes);
for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {
var property = properties_1[_i];
if ((attributes[property] instanceof Function) &&
(attributes[property].name === '_asObjectOrAsStringClosure')) {
attributes[property](node, property);
continue;
}
node.setAttribute(property, attributes[property]);
}
});
}
};
var maxIndices = -1;
var kids = react_1.default.Children.map(arrChildren, function (element) {
// do not clone text nodes, it cause an type is invalid error.
if (element && typeof (element) === "string") {
return element;
}
maxIndices++;
return react_1.default.cloneElement(element, { ref: ref });
function ref(node) {
nodes.push(node);
// string refs are not supported for it is deprecated
// @ts-ignore
if (element.ref instanceof Function) {
// this is for ref in the form: <div ref={element => this.element = element} />
// @ts-ignore
element.ref(node);
}
else {
// @ts-ignore
if (element.ref && typeof (element.ref) === 'object' && Object.keys(element.ref).includes('current')) {
// this is for ref in the form:
// const elementRef = useRef()
// <div ref={elementRef} />
// @ts-ignore
element.ref.current = node;
}
}
// refs are async in react, no callback or promise.
afterRefs(nodes.length - 1 === maxIndices);
}
});
return (react_1.default.createElement(react_1.default.Fragment, null, kids));
};
exports.default = AnyAttribute;
;