UNPKG

@ljcl/storybook-addon-cssprops

Version:
55 lines (54 loc) 2.34 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useInjectCustomProperties = void 0; var React = require("react"); function o2s(style) { var string = ""; Object.keys(style).forEach(function (a) { string += "".concat(a, ": ").concat(style[a], ";"); }); return string; } var useInjectCustomProperties = function (customProperties) { if (customProperties === void 0) { customProperties = {}; } var styles = Object.keys(customProperties) .filter(function (i) { return customProperties[i]; }) .reduce(function (o, key) { var _a; return (__assign(__assign({}, o), (_a = {}, _a["--".concat(key)] = customProperties[key], _a))); }, {}); var previewRef = React.useRef(); React.useLayoutEffect(function () { var _a; var iframe = document.querySelector("#storybook-preview-iframe"); if (iframe) { previewRef.current = (_a = iframe === null || iframe === void 0 ? void 0 : iframe.contentWindow) === null || _a === void 0 ? void 0 : _a.document; } else if (document) { previewRef.current = document; } }, [customProperties]); React.useLayoutEffect(function () { var _a, _b; var stringifiedStyles = o2s(styles); if (stringifiedStyles) { (_b = (_a = previewRef === null || previewRef === void 0 ? void 0 : previewRef.current) === null || _a === void 0 ? void 0 : _a.body) === null || _b === void 0 ? void 0 : _b.setAttribute("style", stringifiedStyles); } return function () { var _a, _b; (_b = (_a = previewRef === null || previewRef === void 0 ? void 0 : previewRef.current) === null || _a === void 0 ? void 0 : _a.body) === null || _b === void 0 ? void 0 : _b.removeAttribute("style"); }; }, [customProperties, styles]); }; exports.useInjectCustomProperties = useInjectCustomProperties;