storybook-addon-pseudo-states 1.14.0 → 1.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,14 @@
1
1
  import { splitSelectors } from "./splitSelectors";
2
- describe("splitSelectors", function () {
3
- test("handles basic selectors", function () {
2
+ describe("splitSelectors", () => {
3
+ test("handles basic selectors", () => {
4
4
  expect(splitSelectors(".a")).toEqual([".a"]);
5
5
  expect(splitSelectors(".a, .b")).toEqual([".a", ".b"]);
6
6
  });
7
- test("supports ::slotted and :is", function () {
7
+ test("supports ::slotted and :is", () => {
8
8
  expect(splitSelectors("::slotted(:is(button, a):active)")).toEqual(["::slotted(:is(button, a):active)"]);
9
9
  expect(splitSelectors("::slotted(:is(button, a):active), ::slotted(:is(button, a):hover)")).toEqual(["::slotted(:is(button, a):active)", "::slotted(:is(button, a):hover)"]);
10
10
  });
11
- test("supports :host", function () {
11
+ test("supports :host", () => {
12
12
  expect(splitSelectors(":host([type='secondary']) ::slotted(:is(button, a)), :host([type='primary']) ::slotted(:is(button, a):active)")).toEqual([":host([type='secondary']) ::slotted(:is(button, a))", ":host([type='primary']) ::slotted(:is(button, a):active)"]);
13
13
  expect(splitSelectors(":host([outline]) ::slotted(:is(button, a):focus-within:focus-visible:not(:active))")).toEqual([":host([outline]) ::slotted(:is(button, a):focus-within:focus-visible:not(:active))"]);
14
14
  });
@@ -1,99 +1,72 @@
1
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
-
3
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
-
5
- function _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; }
6
-
7
- function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
8
-
9
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
10
-
11
- function _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."); }
12
-
13
- function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : 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; }
14
-
15
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
16
-
17
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
18
-
19
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
20
-
21
- function _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); }
22
-
23
- function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
24
-
25
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
26
-
27
- function _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; }
28
-
29
1
  /* eslint-env browser */
30
2
  import { addons, useEffect } from "@storybook/addons";
31
- import { DOCS_RENDERED, STORY_CHANGED, STORY_RENDERED } from "@storybook/core-events";
32
- import { UPDATE_GLOBALS } from '@storybook/core-events';
3
+ import { DOCS_RENDERED, STORY_CHANGED, STORY_RENDERED, UPDATE_GLOBALS } from "@storybook/core-events";
33
4
  import { PSEUDO_STATES } from "./constants";
34
- import { splitSelectors } from "./splitSelectors";
35
- var pseudoStates = Object.values(PSEUDO_STATES);
36
- var matchOne = new RegExp(":(".concat(pseudoStates.join("|"), ")"));
37
- var matchAll = new RegExp(":(".concat(pseudoStates.join("|"), ")"), "g"); // Drops any existing pseudo state classnames that carried over from a previously viewed story
5
+ import { rewriteStyleSheet } from "./rewriteStyleSheet";
6
+ const channel = addons.getChannel();
7
+ const shadowHosts = new Set(); // Drops any existing pseudo state classnames that carried over from a previously viewed story
38
8
  // before adding the new classnames. We do this the old-fashioned way, for IE compatibility.
39
9
 
40
- var applyClasses = function applyClasses(element, classnames) {
41
- var _element$className$sp;
42
-
43
- element.className = (_element$className$sp = element.className.split(" ").filter(function (classname) {
44
- return classname && classname.indexOf("pseudo-") !== 0;
45
- })).concat.apply(_element$className$sp, _toConsumableArray(classnames)).join(" ");
10
+ const applyClasses = (element, classnames) => {
11
+ element.className = element.className.split(" ").filter(classname => classname && classname.indexOf("pseudo-") !== 0).concat(...classnames).join(" ");
46
12
  };
47
13
 
48
- var applyParameter = function applyParameter(element, parameter) {
49
- return applyClasses(element, Object.entries(parameter || {}).filter(function (_ref) {
50
- var _ref2 = _slicedToArray(_ref, 2),
51
- _ = _ref2[0],
52
- value = _ref2[1];
14
+ const applyParameter = (rootElement, parameter) => {
15
+ const map = new Map([[rootElement, new Set()]]);
53
16
 
54
- return value;
55
- }).map(function (_ref3) {
56
- var _ref4 = _slicedToArray(_ref3, 1),
57
- key = _ref4[0];
17
+ const add = (target, state) => map.set(target, new Set([...(map.get(target) || []), state]));
58
18
 
59
- return "pseudo-".concat(PSEUDO_STATES[key]);
60
- }));
19
+ Object.entries(parameter || {}).forEach(_ref => {
20
+ let [state, value] = _ref;
21
+
22
+ if (typeof value === "boolean") {
23
+ // default API - applying pseudo class to root element.
24
+ add(rootElement, value && state);
25
+ } else if (typeof value === "string") {
26
+ // explicit selectors API - applying pseudo class to a specific element
27
+ rootElement.querySelectorAll(value).forEach(el => add(el, state));
28
+ } else if (Array.isArray(value)) {
29
+ // explicit selectors API - we have an array (of strings) recursively handle each one
30
+ value.forEach(sel => rootElement.querySelectorAll(sel).forEach(el => add(el, state)));
31
+ }
32
+ });
33
+ map.forEach((states, target) => {
34
+ const classnames = [];
35
+ states.forEach(key => PSEUDO_STATES[key] && classnames.push("pseudo-".concat(PSEUDO_STATES[key])));
36
+ applyClasses(target, classnames);
37
+ });
61
38
  }; // Traverses ancestry to collect relevant pseudo classnames, and applies them to the shadow host.
62
39
  // Shadow DOM can only access classes on its host. Traversing is needed to mimic the CSS cascade.
63
40
 
64
41
 
65
- var updateShadowHost = function updateShadowHost(shadowHost) {
66
- var classnames = new Set();
42
+ const updateShadowHost = shadowHost => {
43
+ const classnames = new Set();
67
44
 
68
- for (var element = shadowHost.parentElement; element; element = element.parentElement) {
45
+ for (let element = shadowHost.parentElement; element; element = element.parentElement) {
69
46
  if (!element.className) continue;
70
- element.className.split(" ").filter(function (classname) {
71
- return classname.indexOf("pseudo-") === 0;
72
- }).forEach(function (classname) {
73
- return classnames.add(classname);
74
- });
47
+ element.className.split(" ").filter(classname => classname.indexOf("pseudo-") === 0).forEach(classname => classnames.add(classname));
75
48
  }
76
49
 
77
50
  applyClasses(shadowHost, classnames);
78
- }; // Keep track of attached shadow host elements for the current story
79
-
80
-
81
- var shadowHosts = new Set();
82
- addons.getChannel().on(STORY_CHANGED, function () {
83
- return shadowHosts.clear();
84
- }); // Global decorator that rewrites stylesheets and applies classnames to render pseudo styles
85
-
86
- export var withPseudoState = function withPseudoState(StoryFn, _ref5) {
87
- var viewMode = _ref5.viewMode,
88
- parameters = _ref5.parameters,
89
- id = _ref5.id,
90
- globalsArgs = _ref5.globals;
91
- var parameter = parameters.pseudo;
92
- var globals = globalsArgs.pseudo;
93
- var channel = addons.getChannel(); // Sync parameter to globals, used by the toolbar (only in canvas as this
51
+ }; // Global decorator that rewrites stylesheets and applies classnames to render pseudo styles
52
+
53
+
54
+ export const withPseudoState = (StoryFn, _ref2) => {
55
+ let {
56
+ viewMode,
57
+ parameters,
58
+ id,
59
+ globals: globalsArgs
60
+ } = _ref2;
61
+ const {
62
+ pseudo: parameter
63
+ } = parameters;
64
+ const {
65
+ pseudo: globals
66
+ } = globalsArgs; // Sync parameter to globals, used by the toolbar (only in canvas as this
94
67
  // doesn't make sense for docs because many stories are displayed at once)
95
68
 
96
- useEffect(function () {
69
+ useEffect(() => {
97
70
  if (parameter !== globals && viewMode === "story") {
98
71
  channel.emit(UPDATE_GLOBALS, {
99
72
  globals: {
@@ -104,131 +77,31 @@ export var withPseudoState = function withPseudoState(StoryFn, _ref5) {
104
77
  }, [parameter, viewMode]); // Convert selected states to classnames and apply them to the story root element.
105
78
  // Then update each shadow host to redetermine its own pseudo classnames.
106
79
 
107
- useEffect(function () {
108
- var timeout = setTimeout(function () {
109
- var element = document.getElementById(viewMode === "docs" ? "story--".concat(id) : "root");
110
- applyParameter(element, parameter);
80
+ useEffect(() => {
81
+ const timeout = setTimeout(() => {
82
+ const element = document.getElementById(viewMode === "docs" ? "story--".concat(id) : "root");
83
+ applyParameter(element, globals || parameter);
111
84
  shadowHosts.forEach(updateShadowHost);
112
85
  }, 0);
113
- return function () {
114
- return clearTimeout(timeout);
115
- };
116
- }, [parameter, viewMode]);
86
+ return () => clearTimeout(timeout);
87
+ }, [globals, parameter, viewMode]);
117
88
  return StoryFn();
118
- };
119
- var warnings = new Set();
120
-
121
- var warnOnce = function warnOnce(message) {
122
- if (warnings.has(message)) return; // eslint-disable-next-line no-console
123
-
124
- console.warn(message);
125
- warnings.add(message);
126
89
  }; // Rewrite CSS rules for pseudo-states on all stylesheets to add an alternative selector
127
90
 
128
-
129
- function rewriteStyleSheets(shadowRoot) {
91
+ const rewriteStyleSheets = shadowRoot => {
130
92
  var _shadowRoot$adoptedSt;
131
93
 
132
- var styleSheets = shadowRoot ? shadowRoot.styleSheets : document.styleSheets;
94
+ let styleSheets = shadowRoot ? shadowRoot.styleSheets : document.styleSheets;
133
95
  if (shadowRoot !== null && shadowRoot !== void 0 && (_shadowRoot$adoptedSt = shadowRoot.adoptedStyleSheets) !== null && _shadowRoot$adoptedSt !== void 0 && _shadowRoot$adoptedSt.length) styleSheets = shadowRoot.adoptedStyleSheets;
96
+ Array.from(styleSheets).forEach(sheet => rewriteStyleSheet(sheet, shadowRoot, shadowHosts));
97
+ }; // Only track shadow hosts for the current story
134
98
 
135
- var _iterator = _createForOfIteratorHelper(styleSheets),
136
- _step;
137
-
138
- try {
139
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
140
- var sheet = _step.value;
141
-
142
- if (sheet._pseudoStatesRewritten) {
143
- continue;
144
- } else {
145
- sheet._pseudoStatesRewritten = true;
146
- }
147
-
148
- try {
149
- var index = 0;
150
-
151
- var _iterator2 = _createForOfIteratorHelper(sheet.cssRules),
152
- _step2;
153
-
154
- try {
155
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
156
- var _step2$value = _step2.value,
157
- cssText = _step2$value.cssText,
158
- selectorText = _step2$value.selectorText;
159
-
160
- if (matchOne.test(selectorText)) {
161
- var selectors = splitSelectors(selectorText);
162
- var newRule = cssText.replace(selectorText, selectors.flatMap(function (selector) {
163
- if (selector.includes(".pseudo-")) return [];
164
- var states = [];
165
- var plainSelector = selector.replace(matchAll, function (_, state) {
166
- states.push(state);
167
- return "";
168
- });
169
- var stateSelector;
170
-
171
- if (!matchOne.test(selector)) {
172
- return [selector];
173
- }
174
-
175
- if (selector.startsWith(":host(") || selector.startsWith("::slotted(")) {
176
- stateSelector = states.reduce(function (acc, state) {
177
- return acc.replaceAll(":".concat(state), ".pseudo-".concat(state));
178
- }, selector);
179
- } else if (shadowRoot) {
180
- stateSelector = ":host(".concat(states.map(function (s) {
181
- return ".pseudo-".concat(s);
182
- }).join(""), ") ").concat(plainSelector);
183
- } else {
184
- stateSelector = "".concat(states.map(function (s) {
185
- return ".pseudo-".concat(s);
186
- }).join(""), " ").concat(plainSelector);
187
- }
188
-
189
- return [selector, stateSelector];
190
- }).join(", "));
191
- sheet.deleteRule(index);
192
- sheet.insertRule(newRule, index);
193
- if (shadowRoot) shadowHosts.add(shadowRoot.host);
194
- }
195
-
196
- index++;
197
-
198
- if (index > 1000) {
199
- warnOnce("Reached maximum of 1000 pseudo selectors per sheet, skipping the rest.");
200
- break;
201
- }
202
- }
203
- } catch (err) {
204
- _iterator2.e(err);
205
- } finally {
206
- _iterator2.f();
207
- }
208
- } catch (e) {
209
- if (e.toString().includes("cssRules")) {
210
- warnOnce("Can't access cssRules, likely due to CORS restrictions: ".concat(sheet.href));
211
- } else {
212
- // eslint-disable-next-line no-console
213
- console.error(e, sheet.href);
214
- }
215
- }
216
- }
217
- } catch (err) {
218
- _iterator.e(err);
219
- } finally {
220
- _iterator.f();
221
- }
222
- } // Reinitialize CSS enhancements every time the story changes
223
99
 
100
+ channel.on(STORY_CHANGED, () => shadowHosts.clear()); // Reinitialize CSS enhancements every time the story changes
224
101
 
225
- addons.getChannel().on(STORY_RENDERED, function () {
226
- return rewriteStyleSheets();
227
- }); // Reinitialize CSS enhancements every time a docs page is rendered
102
+ channel.on(STORY_RENDERED, () => rewriteStyleSheets()); // Reinitialize CSS enhancements every time a docs page is rendered
228
103
 
229
- addons.getChannel().on(DOCS_RENDERED, function () {
230
- return rewriteStyleSheets();
231
- }); // IE doesn't support shadow DOM
104
+ channel.on(DOCS_RENDERED, () => rewriteStyleSheets()); // IE doesn't support shadow DOM
232
105
 
233
106
  if (Element.prototype.attachShadow) {
234
107
  // Monkeypatch the attachShadow method so we can handle pseudo styles inside shadow DOM
@@ -236,12 +109,12 @@ if (Element.prototype.attachShadow) {
236
109
 
237
110
  Element.prototype.attachShadow = function attachShadow(init) {
238
111
  // Force "open" mode, so we can access the shadowRoot
239
- var shadowRoot = this._attachShadow(_objectSpread(_objectSpread({}, init), {}, {
112
+ const shadowRoot = this._attachShadow({ ...init,
240
113
  mode: "open"
241
- })); // Wait for it to render and apply its styles before rewriting them
114
+ }); // Wait for it to render and apply its styles before rewriting them
242
115
 
243
116
 
244
- requestAnimationFrame(function () {
117
+ requestAnimationFrame(() => {
245
118
  rewriteStyleSheets(shadowRoot);
246
119
  updateShadowHost(shadowRoot.host);
247
120
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "storybook-addon-pseudo-states",
3
- "version": "1.14.0",
3
+ "version": "1.15.1",
4
4
  "description": "CSS pseudo states for Storybook",
5
5
  "keywords": [
6
6
  "storybook-addons",
@@ -38,8 +38,8 @@
38
38
  "@babel/core": "^7.12.3",
39
39
  "@babel/preset-env": "^7.12.1",
40
40
  "@babel/preset-react": "^7.12.5",
41
- "@storybook/addon-docs": "^6.4.19",
42
- "@storybook/react": "^6.4.19",
41
+ "@storybook/addon-docs": "^6.5.0",
42
+ "@storybook/react": "^6.5.0",
43
43
  "auto": "^10.16.8",
44
44
  "babel-loader": "^8.1.0",
45
45
  "chromatic": "^5.6.0",
@@ -50,13 +50,13 @@
50
50
  "rimraf": "^3.0.2"
51
51
  },
52
52
  "peerDependencies": {
53
- "@storybook/addons": "^6.4.19",
54
- "@storybook/api": "^6.4.19",
55
- "@storybook/components": "^6.4.19",
56
- "@storybook/core-events": "^6.4.19",
57
- "@storybook/theming": "^6.4.19",
58
- "react": "^16.8.0 || ^17.0.0",
59
- "react-dom": "^16.8.0 || ^17.0.0"
53
+ "@storybook/addons": "^6.5.0",
54
+ "@storybook/api": "^6.5.0",
55
+ "@storybook/components": "^6.5.0",
56
+ "@storybook/core-events": "^6.5.0",
57
+ "@storybook/theming": "^6.5.0",
58
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0",
59
+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
60
60
  },
61
61
  "peerDependenciesMeta": {
62
62
  "react": {