UNPKG

9.87 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports["default"] = void 0;
7
8var _global = require("global");
9
10var _escapeHtml = _interopRequireDefault(require("escape-html"));
11
12var _clientApi = require("@storybook/client-api");
13
14var _KnobStore = _interopRequireDefault(require("./KnobStore"));
15
16var _shared = require("./shared");
17
18var _converters = require("./converters");
19
20function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
21
22function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
23
24function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
25
26function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
27
28function _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); } }
29
30function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
31
32function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
33
34function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
35
36function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
37
38function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
39
40function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
41
42function _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."); }
43
44function _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); }
45
46function _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; }
47
48function _iterableToArrayLimit(arr, i) { var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
49
50function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
51
52var knobValuesFromUrl = Object.entries((0, _clientApi.getQueryParams)()).reduce(function (acc, _ref) {
53 var _ref2 = _slicedToArray(_ref, 2),
54 k = _ref2[0],
55 v = _ref2[1];
56
57 if (k.includes('knob-')) {
58 return _objectSpread(_objectSpread({}, acc), {}, _defineProperty({}, k.replace('knob-', ''), v));
59 }
60
61 return acc;
62}, {}); // This is used by _mayCallChannel to determine how long to wait to before triggering a panel update
63
64var PANEL_UPDATE_INTERVAL = 400;
65
66function escapeStrings(obj) {
67 if (typeof obj === 'string') {
68 return (0, _escapeHtml["default"])(obj);
69 }
70
71 if (obj == null || _typeof(obj) !== 'object') {
72 return obj;
73 }
74
75 if (Array.isArray(obj)) {
76 var newArray = obj.map(escapeStrings);
77 var didChange = newArray.some(function (newValue, key) {
78 return newValue !== obj[key];
79 });
80 return didChange ? newArray : obj;
81 }
82
83 return Object.entries(obj).reduce(function (acc, _ref3) {
84 var _ref4 = _slicedToArray(_ref3, 2),
85 key = _ref4[0],
86 oldValue = _ref4[1];
87
88 var newValue = escapeStrings(oldValue);
89 return newValue === oldValue ? acc : _objectSpread(_objectSpread({}, acc), {}, _defineProperty({}, key, newValue));
90 }, obj);
91}
92
93var KnobManager = /*#__PURE__*/function () {
94 function KnobManager() {
95 _classCallCheck(this, KnobManager);
96
97 _defineProperty(this, "knobStore", new _KnobStore["default"]());
98
99 _defineProperty(this, "options", {});
100
101 _defineProperty(this, "calling", false);
102 }
103
104 _createClass(KnobManager, [{
105 key: "setChannel",
106 value: function setChannel(channel) {
107 this.channel = channel;
108 }
109 }, {
110 key: "setOptions",
111 value: function setOptions(options) {
112 this.options = options;
113 }
114 }, {
115 key: "getKnobValue",
116 value: function getKnobValue(_ref5) {
117 var value = _ref5.value;
118 return this.options.escapeHTML ? escapeStrings(value) : value;
119 }
120 }, {
121 key: "knob",
122 value: function knob(name, options) {
123 this._mayCallChannel();
124
125 var knobName = options.groupId ? "".concat(name, "_").concat(options.groupId) : name;
126 var knobStore = this.knobStore;
127 var existingKnob = knobStore.get(knobName); // We need to return the value set by the knob editor via this.
128 // Normally the knobs are reset and so re-use is safe as long as the types match
129 // when in storyshots, though the change event isn't called and so the knobs aren't reset, making this code fail
130 // so always create a new knob when in storyshots
131
132 if (existingKnob && options.type === existingKnob.type && _global.navigator && ( // userAgent is not set in react-native
133 !_global.navigator.userAgent || !_global.navigator.userAgent.includes('jsdom'))) {
134 var value = options.value,
135 restOptions = _objectWithoutProperties(options, ["value"]);
136
137 knobStore.update(knobName, restOptions);
138 return this.getKnobValue(existingKnob);
139 }
140
141 var knobInfo = _objectSpread(_objectSpread({}, options), {}, {
142 name: knobName,
143 label: name
144 });
145
146 if (knobValuesFromUrl[knobName]) {
147 var _value = _converters.deserializers[options.type](knobValuesFromUrl[knobName]);
148
149 knobInfo.defaultValue = _value;
150 knobInfo.value = _value;
151 delete knobValuesFromUrl[knobName];
152 } else {
153 knobInfo.defaultValue = options.value;
154 }
155
156 knobStore.set(knobName, knobInfo);
157 return this.getKnobValue(knobStore.get(knobName));
158 }
159 }, {
160 key: "_mayCallChannel",
161 value: function _mayCallChannel() {
162 var _this = this;
163
164 // Re rendering of the story may cause changes to the knobStore. Some new knobs maybe added and
165 // Some knobs may go unused. So we need to update the panel accordingly. For example remove the
166 // unused knobs from the panel. This function sends the `setKnobs` message to the channel
167 // triggering a panel re-render.
168 if (!this.channel) {
169 // to prevent call to undefined channel and therefore throwing TypeError
170 return;
171 }
172
173 if (this.calling) {
174 // If a call to channel has already registered ignore this call.
175 // Once the previous call is completed all the changes to knobStore including the one that
176 // triggered this, will be added to the panel.
177 // This avoids emitting to the channel within very short periods of time.
178 return;
179 }
180
181 this.calling = true;
182 var timestamp = +new Date();
183 setTimeout(function () {
184 _this.calling = false; // emit to the channel and trigger a panel re-render
185
186 if (_this.channel) _this.channel.emit(_shared.SET, {
187 knobs: _this.knobStore.getAll(),
188 timestamp: timestamp
189 });
190 }, PANEL_UPDATE_INTERVAL);
191 }
192 }]);
193
194 return KnobManager;
195}();
196
197exports["default"] = KnobManager;
\No newline at end of file