storybook
Version:
Storybook: Develop, document, and test UI components in isolation
9,779 lines • 346 kB
JavaScript
import {
_defineProperty,
_objectWithoutProperties
} from "../../_browser-chunks/chunk-L2D73C6Z.js";
import "../../_browser-chunks/chunk-VAMFPZY3.js";
import {
dequal,
uniq
} from "../../_browser-chunks/chunk-SYS437NN.js";
import {
getControlId,
getControlSetterButtonId
} from "../../_browser-chunks/chunk-U46RQHA4.js";
import {
ADDON_ID as ADDON_ID3,
ADDON_ID2 as ADDON_ID4,
ADDON_ID3 as ADDON_ID5,
DEFAULT_BACKGROUNDS,
PARAM_KEY as PARAM_KEY3,
PARAM_KEY3 as PARAM_KEY4,
TOOL_ID as TOOL_ID2
} from "../../_browser-chunks/chunk-CADGRH3P.js";
import {
curriedDarken$1,
curriedLighten$1,
curriedOpacify$1,
curriedTransparentize$1,
rgba
} from "../../_browser-chunks/chunk-OBXWFEPB.js";
import {
_extends
} from "../../_browser-chunks/chunk-MH6AXFXB.js";
import {
EVENTS
} from "../../_browser-chunks/chunk-SN4J4IQ3.js";
import {
require_ansi_to_html
} from "../../_browser-chunks/chunk-F4Q6SGTB.js";
import {
cloneDeep,
pickBy
} from "../../_browser-chunks/chunk-UTNZYD2N.js";
import "../../_browser-chunks/chunk-FSBVR7H5.js";
import {
require_memoizerific
} from "../../_browser-chunks/chunk-NVV6MIOE.js";
import {
ADDON_ID,
CLEAR_ID,
EVENT_ID,
PANEL_ID,
PARAM_KEY
} from "../../_browser-chunks/chunk-XW6KSYKF.js";
import {
MINIMAL_VIEWPORTS,
responsiveViewport
} from "../../_browser-chunks/chunk-TMDZCWME.js";
import {
ADDON_ID as ADDON_ID2,
PARAM_KEY as PARAM_KEY2,
TOOL_ID
} from "../../_browser-chunks/chunk-HHW4FUMO.js";
import {
__name,
__toESM
} from "../../_browser-chunks/chunk-MM7DTO55.js";
// src/core-server/presets/common-manager.ts
import { global as global3 } from "@storybook/global";
import { addons as addons8 } from "storybook/manager-api";
// src/controls/manager.tsx
import React40 from "react";
import { AddonPanel } from "storybook/internal/components";
import { SAVE_STORY_REQUEST, SAVE_STORY_RESPONSE } from "storybook/internal/core-events";
import { FailedIcon, PassedIcon } from "@storybook/icons";
import { addons, experimental_requestResponse, types } from "storybook/manager-api";
import { color } from "storybook/theming";
// src/controls/components/ControlsPanel.tsx
import React38, { useEffect as useEffect11, useMemo as useMemo3, useState as useState14 } from "react";
import { global } from "@storybook/global";
import {
useArgTypes,
useArgs,
useGlobals,
useParameter,
useStorybookApi,
useStorybookState
} from "storybook/manager-api";
import { styled as styled30 } from "storybook/theming";
// ../addons/docs/src/blocks/components/ArgsTable/ArgsTable.tsx
import React36 from "react";
import { once } from "storybook/internal/client-logger";
import { IconButton as IconButton3, Link as Link3, ResetWrapper as ResetWrapper3 } from "storybook/internal/components";
import { includeConditionalArg } from "storybook/internal/csf";
import { DocumentIcon as DocumentIcon2, UndoIcon } from "@storybook/icons";
import { styled as styled28 } from "storybook/theming";
// ../addons/docs/src/blocks/components/Source.tsx
import React2 from "react";
import { SyntaxHighlighter } from "storybook/internal/components";
import {
ThemeProvider,
convert,
ignoreSsrWarning,
styled as styled2,
themes,
useTheme
} from "storybook/theming";
// ../addons/docs/src/blocks/components/EmptyBlock.tsx
import React from "react";
import { withReset } from "storybook/internal/components";
import { styled } from "storybook/theming";
var Wrapper = styled.div(withReset, ({ theme: theme3 }) => ({
backgroundColor: theme3.base === "light" ? "rgba(0,0,0,.01)" : "rgba(255,255,255,.01)",
borderRadius: theme3.appBorderRadius,
border: `1px dashed ${theme3.appBorderColor}`,
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: 20,
margin: "25px 0 40px",
color: curriedTransparentize$1(0.3, theme3.color.defaultText),
fontSize: theme3.typography.size.s2
}));
var EmptyBlock = /* @__PURE__ */ __name((props) => React.createElement(Wrapper, { ...props, className: "docblock-emptyblock sb-unstyled" }), "EmptyBlock");
// ../addons/docs/src/blocks/components/Source.tsx
var StyledSyntaxHighlighter = styled2(
SyntaxHighlighter
)(({ theme: theme3 }) => ({
// DocBlocks-specific styling and overrides
fontSize: `${theme3.typography.size.s2 - 1}px`,
lineHeight: "19px",
margin: "25px 0 40px",
borderRadius: theme3.appBorderRadius,
boxShadow: theme3.base === "light" ? "rgba(0, 0, 0, 0.10) 0 1px 3px 0" : "rgba(0, 0, 0, 0.20) 0 2px 5px 0",
"pre.prismjs": {
padding: 20,
background: "inherit"
}
}));
var SourceSkeletonWrapper = styled2.div(({ theme: theme3 }) => ({
background: theme3.background.content,
borderRadius: theme3.appBorderRadius,
border: `1px solid ${theme3.appBorderColor}`,
boxShadow: theme3.base === "light" ? "rgba(0, 0, 0, 0.10) 0 1px 3px 0" : "rgba(0, 0, 0, 0.20) 0 2px 5px 0",
margin: "25px 0 40px",
padding: "20px 20px 20px 22px"
}));
var SourceSkeletonPlaceholder = styled2.div(({ theme: theme3 }) => ({
animation: `${theme3.animation.glow} 1.5s ease-in-out infinite`,
background: theme3.appBorderColor,
height: 17,
marginTop: 1,
width: "60%",
[`&:first-child${ignoreSsrWarning}`]: {
margin: 0
}
}));
var SourceSkeleton = /* @__PURE__ */ __name(() => React2.createElement(SourceSkeletonWrapper, null, React2.createElement(SourceSkeletonPlaceholder, null), React2.createElement(SourceSkeletonPlaceholder, { style: { width: "80%" } }), React2.createElement(SourceSkeletonPlaceholder, { style: { width: "30%" } }), React2.createElement(SourceSkeletonPlaceholder, { style: { width: "80%" } })), "SourceSkeleton");
var Source = /* @__PURE__ */ __name(({
isLoading,
error,
language,
code,
dark,
format = true,
...rest
}) => {
const { typography: typography4 } = useTheme();
if (isLoading) {
return React2.createElement(SourceSkeleton, null);
}
if (error) {
return React2.createElement(EmptyBlock, null, error);
}
const syntaxHighlighter = React2.createElement(
StyledSyntaxHighlighter,
{
bordered: true,
copyable: true,
format,
language: language ?? "jsx",
className: "docblock-source sb-unstyled",
...rest
},
code
);
if (typeof dark === "undefined") {
return syntaxHighlighter;
}
const overrideTheme = dark ? themes.dark : themes.light;
return React2.createElement(
ThemeProvider,
{
theme: convert({
...overrideTheme,
fontCode: typography4.fonts.mono,
fontBase: typography4.fonts.base
})
},
syntaxHighlighter
);
}, "Source");
// ../addons/docs/src/blocks/components/DocsPage.tsx
import React3 from "react";
import { withReset as withReset2 } from "storybook/internal/components";
import { styled as styled3 } from "storybook/theming";
var toGlobalSelector = /* @__PURE__ */ __name((element) => `& :where(${element}:not(.sb-anchor, .sb-unstyled, .sb-unstyled ${element}))`, "toGlobalSelector");
var breakpoint = 600;
var Title = styled3.h1(withReset2, ({ theme: theme3 }) => ({
color: theme3.color.defaultText,
fontSize: theme3.typography.size.m3,
fontWeight: theme3.typography.weight.bold,
lineHeight: "32px",
[`@media (min-width: ${breakpoint}px)`]: {
fontSize: theme3.typography.size.l1,
lineHeight: "36px",
marginBottom: "16px"
}
}));
var Subtitle = styled3.h2(withReset2, ({ theme: theme3 }) => ({
fontWeight: theme3.typography.weight.regular,
fontSize: theme3.typography.size.s3,
lineHeight: "20px",
borderBottom: "none",
marginBottom: 15,
[`@media (min-width: ${breakpoint}px)`]: {
fontSize: theme3.typography.size.m1,
lineHeight: "28px",
marginBottom: 24
},
color: curriedTransparentize$1(0.25, theme3.color.defaultText)
}));
var DocsContent = styled3.div(({ theme: theme3 }) => {
const reset = {
fontFamily: theme3.typography.fonts.base,
fontSize: theme3.typography.size.s3,
margin: 0,
WebkitFontSmoothing: "antialiased",
MozOsxFontSmoothing: "grayscale",
WebkitTapHighlightColor: "rgba(0, 0, 0, 0)",
WebkitOverflowScrolling: "touch"
};
const headers = {
margin: "20px 0 8px",
padding: 0,
cursor: "text",
position: "relative",
color: theme3.color.defaultText,
"&:first-of-type": {
marginTop: 0,
paddingTop: 0
},
"&:hover a.anchor": {
textDecoration: "none"
},
"& code": {
fontSize: "inherit"
}
};
const code = {
lineHeight: 1,
margin: "0 2px",
padding: "3px 5px",
whiteSpace: "nowrap",
borderRadius: 3,
fontSize: theme3.typography.size.s2 - 1,
border: theme3.base === "light" ? `1px solid ${theme3.color.mediumlight}` : `1px solid ${theme3.color.darker}`,
color: theme3.base === "light" ? curriedTransparentize$1(0.1, theme3.color.defaultText) : curriedTransparentize$1(0.3, theme3.color.defaultText),
backgroundColor: theme3.base === "light" ? theme3.color.lighter : theme3.color.border
};
return {
maxWidth: 1e3,
width: "100%",
minWidth: 0,
[toGlobalSelector("a")]: {
...reset,
fontSize: "inherit",
lineHeight: "24px",
color: theme3.color.secondary,
textDecoration: "none",
"&.absent": {
color: "#cc0000"
},
"&.anchor": {
display: "block",
paddingLeft: 30,
marginLeft: -30,
cursor: "pointer",
position: "absolute",
top: 0,
left: 0,
bottom: 0
}
},
[toGlobalSelector("blockquote")]: {
...reset,
margin: "16px 0",
borderLeft: `4px solid ${theme3.color.medium}`,
padding: "0 15px",
color: theme3.color.dark,
"& > :first-of-type": {
marginTop: 0
},
"& > :last-child": {
marginBottom: 0
}
},
[toGlobalSelector("div")]: reset,
[toGlobalSelector("dl")]: {
...reset,
margin: "16px 0",
padding: 0,
"& dt": {
fontSize: "14px",
fontWeight: "bold",
fontStyle: "italic",
padding: 0,
margin: "16px 0 4px"
},
"& dt:first-of-type": {
padding: 0
},
"& dt > :first-of-type": {
marginTop: 0
},
"& dt > :last-child": {
marginBottom: 0
},
"& dd": {
margin: "0 0 16px",
padding: "0 15px"
},
"& dd > :first-of-type": {
marginTop: 0
},
"& dd > :last-child": {
marginBottom: 0
}
},
[toGlobalSelector("h1")]: {
...reset,
...headers,
fontSize: `${theme3.typography.size.l1}px`,
fontWeight: theme3.typography.weight.bold
},
[toGlobalSelector("h2")]: {
...reset,
...headers,
fontSize: `${theme3.typography.size.m2}px`,
paddingBottom: 4,
borderBottom: `1px solid ${theme3.appBorderColor}`
},
[toGlobalSelector("h3")]: {
...reset,
...headers,
fontSize: `${theme3.typography.size.m1}px`,
fontWeight: theme3.typography.weight.bold
},
[toGlobalSelector("h4")]: {
...reset,
...headers,
fontSize: `${theme3.typography.size.s3}px`
},
[toGlobalSelector("h5")]: {
...reset,
...headers,
fontSize: `${theme3.typography.size.s2}px`
},
[toGlobalSelector("h6")]: {
...reset,
...headers,
fontSize: `${theme3.typography.size.s2}px`,
color: theme3.color.dark
},
[toGlobalSelector("hr")]: {
border: "0 none",
borderTop: `1px solid ${theme3.appBorderColor}`,
height: 4,
padding: 0
},
[toGlobalSelector("img")]: {
maxWidth: "100%"
},
[toGlobalSelector("li")]: {
...reset,
fontSize: theme3.typography.size.s2,
color: theme3.color.defaultText,
lineHeight: "24px",
"& + li": {
marginTop: ".25em"
},
"& ul, & ol": {
marginTop: ".25em",
marginBottom: 0
},
"& code": code
},
[toGlobalSelector("ol")]: {
...reset,
margin: "16px 0",
paddingLeft: 30,
"& :first-of-type": {
marginTop: 0
},
"& :last-child": {
marginBottom: 0
}
},
[toGlobalSelector("p")]: {
...reset,
margin: "16px 0",
fontSize: theme3.typography.size.s2,
lineHeight: "24px",
color: theme3.color.defaultText,
"& code": code
},
[toGlobalSelector("pre")]: {
...reset,
// reset
fontFamily: theme3.typography.fonts.mono,
WebkitFontSmoothing: "antialiased",
MozOsxFontSmoothing: "grayscale",
lineHeight: "18px",
padding: "11px 1rem",
whiteSpace: "pre-wrap",
color: "inherit",
borderRadius: 3,
margin: "1rem 0",
"&:not(.prismjs)": {
background: "transparent",
border: "none",
borderRadius: 0,
padding: 0,
margin: 0
},
"& pre, &.prismjs": {
padding: 15,
margin: 0,
whiteSpace: "pre-wrap",
color: "inherit",
fontSize: "13px",
lineHeight: "19px",
code: {
color: "inherit",
fontSize: "inherit"
}
},
"& code": {
whiteSpace: "pre"
},
"& code, & tt": {
border: "none"
}
},
[toGlobalSelector("span")]: {
...reset,
"&.frame": {
display: "block",
overflow: "hidden",
"& > span": {
border: `1px solid ${theme3.color.medium}`,
display: "block",
float: "left",
overflow: "hidden",
margin: "13px 0 0",
padding: 7,
width: "auto"
},
"& span img": {
display: "block",
float: "left"
},
"& span span": {
clear: "both",
color: theme3.color.darkest,
display: "block",
padding: "5px 0 0"
}
},
"&.align-center": {
display: "block",
overflow: "hidden",
clear: "both",
"& > span": {
display: "block",
overflow: "hidden",
margin: "13px auto 0",
textAlign: "center"
},
"& span img": {
margin: "0 auto",
textAlign: "center"
}
},
"&.align-right": {
display: "block",
overflow: "hidden",
clear: "both",
"& > span": {
display: "block",
overflow: "hidden",
margin: "13px 0 0",
textAlign: "right"
},
"& span img": {
margin: 0,
textAlign: "right"
}
},
"&.float-left": {
display: "block",
marginRight: 13,
overflow: "hidden",
float: "left",
"& span": {
margin: "13px 0 0"
}
},
"&.float-right": {
display: "block",
marginLeft: 13,
overflow: "hidden",
float: "right",
"& > span": {
display: "block",
overflow: "hidden",
margin: "13px auto 0",
textAlign: "right"
}
}
},
[toGlobalSelector("table")]: {
...reset,
margin: "16px 0",
fontSize: theme3.typography.size.s2,
lineHeight: "24px",
padding: 0,
borderCollapse: "collapse",
"& tr": {
borderTop: `1px solid ${theme3.appBorderColor}`,
backgroundColor: theme3.appContentBg,
margin: 0,
padding: 0
},
"& tr:nth-of-type(2n)": {
backgroundColor: theme3.base === "dark" ? theme3.color.darker : theme3.color.lighter
},
"& tr th": {
fontWeight: "bold",
color: theme3.color.defaultText,
border: `1px solid ${theme3.appBorderColor}`,
margin: 0,
padding: "6px 13px"
},
"& tr td": {
border: `1px solid ${theme3.appBorderColor}`,
color: theme3.color.defaultText,
margin: 0,
padding: "6px 13px"
},
"& tr th :first-of-type, & tr td :first-of-type": {
marginTop: 0
},
"& tr th :last-child, & tr td :last-child": {
marginBottom: 0
}
},
[toGlobalSelector("ul")]: {
...reset,
margin: "16px 0",
paddingLeft: 30,
"& :first-of-type": {
marginTop: 0
},
"& :last-child": {
marginBottom: 0
},
listStyle: "disc"
}
};
});
var DocsWrapper = styled3.div(({ theme: theme3 }) => ({
background: theme3.background.content,
display: "flex",
flexDirection: "row-reverse",
justifyContent: "center",
padding: "4rem 20px",
minHeight: "100vh",
boxSizing: "border-box",
gap: "3rem",
[`@media (min-width: ${breakpoint}px)`]: {}
}));
// ../addons/docs/src/blocks/components/Preview.tsx
import React8, { Children, useCallback, useContext as useContext2, useState as useState3 } from "react";
import { ActionBar, Zoom } from "storybook/internal/components";
import { styled as styled6 } from "storybook/theming";
// ../addons/docs/src/blocks/blocks/DocsContext.ts
import { createContext } from "react";
if (globalThis && globalThis.__DOCS_CONTEXT__ === void 0) {
globalThis.__DOCS_CONTEXT__ = createContext(null);
globalThis.__DOCS_CONTEXT__.displayName = "DocsContext";
}
var DocsContext = globalThis ? globalThis.__DOCS_CONTEXT__ : createContext(null);
// ../addons/docs/src/blocks/blocks/Story.tsx
import React4, { useContext } from "react";
// ../addons/docs/src/blocks/blocks/useStory.ts
import { useEffect, useState } from "react";
// ../addons/docs/src/blocks/blocks/Story.tsx
var getStoryId = /* @__PURE__ */ __name((props, context) => {
const { of, meta } = props;
if ("of" in props && of === void 0) {
throw new Error("Unexpected `of={undefined}`, did you mistype a CSF file reference?");
}
if (meta) {
context.referenceMeta(meta, false);
}
const resolved = context.resolveOf(of || "story", ["story"]);
return resolved.story.id;
}, "getStoryId");
// ../addons/docs/src/blocks/components/BlockBackgroundStyles.tsx
var getBlockBackgroundStyle = /* @__PURE__ */ __name((theme3) => ({
borderRadius: theme3.appBorderRadius,
background: theme3.background.content,
boxShadow: theme3.base === "light" ? "rgba(0, 0, 0, 0.10) 0 1px 3px 0" : "rgba(0, 0, 0, 0.20) 0 2px 5px 0",
border: `1px solid ${theme3.appBorderColor}`
}), "getBlockBackgroundStyle");
// ../addons/docs/src/blocks/components/Story.tsx
import React6, { useEffect as useEffect2, useRef, useState as useState2 } from "react";
import { ErrorFormatter, Loader, getStoryHref } from "storybook/internal/components";
import { styled as styled4 } from "storybook/theming";
// ../addons/docs/src/blocks/components/IFrame.tsx
import React5, { Component } from "react";
var { window: globalWindow } = globalThis;
// ../addons/docs/src/blocks/components/ZoomContext.tsx
import { createContext as createContext2 } from "react";
var ZoomContext = createContext2({
scale: 1
});
// ../addons/docs/src/blocks/components/Story.tsx
var { PREVIEW_URL } = globalThis;
var ErrorMessage = styled4.strong(({ theme: theme3 }) => ({
color: theme3.color.orange
}));
// ../addons/docs/src/blocks/components/Toolbar.tsx
import React7 from "react";
import { FlexBar, IconButton, getStoryHref as getStoryHref2 } from "storybook/internal/components";
import { ShareAltIcon, ZoomIcon, ZoomOutIcon, ZoomResetIcon } from "@storybook/icons";
import { styled as styled5 } from "storybook/theming";
var Bar = styled5(FlexBar)({
position: "absolute",
left: 0,
right: 0,
top: 0,
transition: "transform .2s linear"
});
var Wrapper2 = styled5.div({
display: "flex",
alignItems: "center",
gap: 4
});
var IconPlaceholder = styled5.div(({ theme: theme3 }) => ({
width: 14,
height: 14,
borderRadius: 2,
margin: "0 7px",
backgroundColor: theme3.appBorderColor,
animation: `${theme3.animation.glow} 1.5s ease-in-out infinite`
}));
var Toolbar = /* @__PURE__ */ __name(({
isLoading,
storyId,
baseUrl,
zoom,
resetZoom,
...rest
}) => React7.createElement(Bar, { ...rest }, React7.createElement(Wrapper2, { key: "left" }, isLoading ? [1, 2, 3].map((key) => React7.createElement(IconPlaceholder, { key })) : React7.createElement(React7.Fragment, null, React7.createElement(
IconButton,
{
key: "zoomin",
onClick: (e2) => {
e2.preventDefault();
zoom(0.8);
},
title: "Zoom in"
},
React7.createElement(ZoomIcon, null)
), React7.createElement(
IconButton,
{
key: "zoomout",
onClick: (e2) => {
e2.preventDefault();
zoom(1.25);
},
title: "Zoom out"
},
React7.createElement(ZoomOutIcon, null)
), React7.createElement(
IconButton,
{
key: "zoomreset",
onClick: (e2) => {
e2.preventDefault();
resetZoom();
},
title: "Reset zoom"
},
React7.createElement(ZoomResetIcon, null)
))), isLoading ? React7.createElement(Wrapper2, { key: "right" }, React7.createElement(IconPlaceholder, null)) : baseUrl && storyId && React7.createElement(Wrapper2, { key: "right" }, React7.createElement(IconButton, { key: "opener", asChild: true }, React7.createElement(
"a",
{
href: getStoryHref2(baseUrl, storyId),
target: "_blank",
rel: "noopener noreferrer",
"aria-label": "Open canvas in new tab"
},
React7.createElement(ShareAltIcon, null)
)))), "Toolbar");
// ../addons/docs/src/blocks/components/Preview.tsx
var ChildrenContainer = styled6.div(
({ isColumn, columns, layout }) => ({
display: isColumn || !columns ? "block" : "flex",
position: "relative",
flexWrap: "wrap",
overflow: "auto",
flexDirection: isColumn ? "column" : "row",
"& .innerZoomElementWrapper > *": isColumn ? {
width: layout !== "fullscreen" ? "calc(100% - 20px)" : "100%",
display: "block"
} : {
maxWidth: layout !== "fullscreen" ? "calc(100% - 20px)" : "100%",
display: "inline-block"
}
}),
({ layout = "padded", inline }) => layout === "centered" || layout === "padded" ? {
padding: inline ? "32px 22px" : "0px",
"& .innerZoomElementWrapper > *": {
width: "auto",
border: "8px solid transparent!important"
}
} : {},
({ layout = "padded", inline }) => layout === "centered" && inline ? {
display: "flex",
justifyContent: "center",
justifyItems: "center",
alignContent: "center",
alignItems: "center"
} : {},
({ columns }) => columns && columns > 1 ? { ".innerZoomElementWrapper > *": { minWidth: `calc(100% / ${columns} - 20px)` } } : {}
);
var StyledSource = styled6(Source)(({ theme: theme3 }) => ({
margin: 0,
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
borderBottomLeftRadius: theme3.appBorderRadius,
borderBottomRightRadius: theme3.appBorderRadius,
border: "none",
background: theme3.base === "light" ? "rgba(0, 0, 0, 0.85)" : curriedDarken$1(0.05, theme3.background.content),
color: theme3.color.lightest,
button: {
background: theme3.base === "light" ? "rgba(0, 0, 0, 0.85)" : curriedDarken$1(0.05, theme3.background.content)
}
}));
var PreviewContainer = styled6.div(
({ theme: theme3, withSource, isExpanded }) => ({
position: "relative",
overflow: "hidden",
margin: "25px 0 40px",
...getBlockBackgroundStyle(theme3),
borderBottomLeftRadius: withSource && isExpanded && 0,
borderBottomRightRadius: withSource && isExpanded && 0,
borderBottomWidth: isExpanded && 0,
"h3 + &": {
marginTop: "16px"
}
}),
({ withToolbar }) => withToolbar && { paddingTop: 40 }
);
var getSource = /* @__PURE__ */ __name((withSource, expanded, setExpanded) => {
switch (true) {
case !!(withSource && withSource.error): {
return {
source: null,
actionItem: {
title: "No code available",
className: "docblock-code-toggle docblock-code-toggle--disabled",
disabled: true,
onClick: /* @__PURE__ */ __name(() => setExpanded(false), "onClick")
}
};
}
case expanded: {
return {
source: React8.createElement(StyledSource, { ...withSource, dark: true }),
actionItem: {
title: "Hide code",
className: "docblock-code-toggle docblock-code-toggle--expanded",
onClick: /* @__PURE__ */ __name(() => setExpanded(false), "onClick")
}
};
}
default: {
return {
source: React8.createElement(StyledSource, { ...withSource, dark: true }),
actionItem: {
title: "Show code",
className: "docblock-code-toggle",
onClick: /* @__PURE__ */ __name(() => setExpanded(true), "onClick")
}
};
}
}
}, "getSource");
function getChildProps(children) {
if (Children.count(children) === 1) {
const elt = children;
if (elt.props) {
return elt.props;
}
}
return null;
}
__name(getChildProps, "getChildProps");
var PositionedToolbar = styled6(Toolbar)({
position: "absolute",
top: 0,
left: 0,
right: 0,
height: 40
});
var Relative = styled6.div({
overflow: "hidden",
position: "relative"
});
var Preview = /* @__PURE__ */ __name(({
isLoading,
isColumn,
columns,
children,
withSource,
withToolbar = false,
isExpanded = false,
additionalActions,
className,
layout = "padded",
inline = false,
...props
}) => {
const [expanded, setExpanded] = useState3(isExpanded);
const { source, actionItem } = getSource(withSource, expanded, setExpanded);
const [scale, setScale] = useState3(1);
const previewClasses = [className].concat(["sbdocs", "sbdocs-preview", "sb-unstyled"]);
const defaultActionItems = withSource ? [actionItem] : [];
const [additionalActionItems, setAdditionalActionItems] = useState3(
additionalActions ? [...additionalActions] : []
);
const actionItems = [...defaultActionItems, ...additionalActionItems];
const { window: globalWindow3 } = globalThis;
const context = useContext2(DocsContext);
const copyToClipboard = useCallback(async (text) => {
const { createCopyToClipboardFunction } = await import("storybook/internal/components");
createCopyToClipboardFunction();
}, []);
const onCopyCapture = /* @__PURE__ */ __name((e2) => {
const selection = globalWindow3.getSelection();
if (selection && selection.type === "Range") {
return;
}
e2.preventDefault();
if (additionalActionItems.filter((item) => item.title === "Copied").length === 0) {
copyToClipboard(source?.props.code ?? "").then(() => {
setAdditionalActionItems([
...additionalActionItems,
{
title: "Copied",
onClick: /* @__PURE__ */ __name(() => {
}, "onClick")
}
]);
globalWindow3.setTimeout(
() => setAdditionalActionItems(
additionalActionItems.filter((item) => item.title !== "Copied")
),
1500
);
});
}
}, "onCopyCapture");
const childProps = getChildProps(children);
return React8.createElement(
PreviewContainer,
{
...{ withSource, withToolbar },
...props,
className: previewClasses.join(" ")
},
withToolbar && React8.createElement(
PositionedToolbar,
{
isLoading,
border: true,
zoom: (z2) => setScale(scale * z2),
resetZoom: () => setScale(1),
storyId: !isLoading && childProps ? getStoryId(childProps, context) : void 0,
baseUrl: "./iframe.html"
}
),
React8.createElement(ZoomContext.Provider, { value: { scale } }, React8.createElement(Relative, { className: "docs-story", onCopyCapture: withSource && onCopyCapture }, React8.createElement(
ChildrenContainer,
{
isColumn: isColumn || !Array.isArray(children),
columns,
layout,
inline
},
React8.createElement(Zoom.Element, { centered: layout === "centered", scale: inline ? scale : 1 }, Array.isArray(children) ? children.map((child, i2) => React8.createElement("div", { key: i2 }, child)) : React8.createElement("div", null, children))
), React8.createElement(ActionBar, { actionItems }))),
withSource && expanded && source
);
}, "Preview");
var StyledPreview = styled6(Preview)(() => ({
".docs-story": {
paddingTop: 32,
paddingBottom: 40
}
}));
// ../addons/docs/src/blocks/components/ArgsTable/TabbedArgsTable.tsx
import React9 from "react";
import { TabsState } from "storybook/internal/components";
// ../addons/docs/src/blocks/components/Typeset.tsx
import React10 from "react";
import { withReset as withReset3 } from "storybook/internal/components";
import { styled as styled7 } from "storybook/theming";
var Label = styled7.div(({ theme: theme3 }) => ({
marginRight: 30,
fontSize: `${theme3.typography.size.s1}px`,
color: theme3.base === "light" ? curriedTransparentize$1(0.4, theme3.color.defaultText) : curriedTransparentize$1(0.6, theme3.color.defaultText)
}));
var Sample = styled7.div({
overflow: "hidden",
whiteSpace: "nowrap",
textOverflow: "ellipsis"
});
var TypeSpecimen = styled7.div({
display: "flex",
flexDirection: "row",
alignItems: "baseline",
"&:not(:last-child)": { marginBottom: "1rem" }
});
var Wrapper3 = styled7.div(withReset3, ({ theme: theme3 }) => ({
...getBlockBackgroundStyle(theme3),
margin: "25px 0 40px",
padding: "30px 20px"
}));
// ../addons/docs/src/blocks/components/ColorPalette.tsx
import React11 from "react";
import { ResetWrapper } from "storybook/internal/components";
import { styled as styled8 } from "storybook/theming";
var ItemTitle = styled8.div(({ theme: theme3 }) => ({
fontWeight: theme3.typography.weight.bold,
color: theme3.color.defaultText
}));
var ItemSubtitle = styled8.div(({ theme: theme3 }) => ({
color: theme3.base === "light" ? curriedTransparentize$1(0.2, theme3.color.defaultText) : curriedTransparentize$1(0.6, theme3.color.defaultText)
}));
var ItemDescription = styled8.div({
flex: "0 0 30%",
lineHeight: "20px",
marginTop: 5
});
var SwatchLabel = styled8.div(({ theme: theme3 }) => ({
flex: 1,
textAlign: "center",
fontFamily: theme3.typography.fonts.mono,
fontSize: theme3.typography.size.s1,
lineHeight: 1,
overflow: "hidden",
color: theme3.base === "light" ? curriedTransparentize$1(0.4, theme3.color.defaultText) : curriedTransparentize$1(0.6, theme3.color.defaultText),
"> div": {
display: "inline-block",
overflow: "hidden",
maxWidth: "100%",
textOverflow: "ellipsis"
},
span: {
display: "block",
marginTop: 2
}
}));
var SwatchLabels = styled8.div({
display: "flex",
flexDirection: "row"
});
var Swatch = styled8.div(({ background }) => ({
position: "relative",
flex: 1,
"&::before": {
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%",
background,
content: '""'
}
}));
var SwatchColors = styled8.div(({ theme: theme3 }) => ({
...getBlockBackgroundStyle(theme3),
display: "flex",
flexDirection: "row",
height: 50,
marginBottom: 5,
overflow: "hidden",
backgroundColor: "white",
backgroundImage: `repeating-linear-gradient(-45deg, #ccc, #ccc 1px, #fff 1px, #fff 16px)`,
backgroundClip: "padding-box"
}));
var SwatchSpecimen = styled8.div({
display: "flex",
flexDirection: "column",
flex: 1,
position: "relative",
marginBottom: 30
});
var Swatches = styled8.div({
flex: 1,
display: "flex",
flexDirection: "row"
});
var Item = styled8.div({
display: "flex",
alignItems: "flex-start"
});
var ListName = styled8.div({
flex: "0 0 30%"
});
var ListSwatches = styled8.div({
flex: 1
});
var ListHeading = styled8.div(({ theme: theme3 }) => ({
display: "flex",
flexDirection: "row",
alignItems: "center",
paddingBottom: 20,
fontWeight: theme3.typography.weight.bold,
color: theme3.base === "light" ? curriedTransparentize$1(0.4, theme3.color.defaultText) : curriedTransparentize$1(0.6, theme3.color.defaultText)
}));
var List = styled8.div(({ theme: theme3 }) => ({
fontSize: theme3.typography.size.s2,
lineHeight: `20px`,
display: "flex",
flexDirection: "column"
}));
// ../addons/docs/src/blocks/components/IconGallery.tsx
import React12 from "react";
import { ResetWrapper as ResetWrapper2 } from "storybook/internal/components";
import { styled as styled9 } from "storybook/theming";
var ItemLabel = styled9.div(({ theme: theme3 }) => ({
fontFamily: theme3.typography.fonts.base,
fontSize: theme3.typography.size.s1,
color: theme3.color.defaultText,
marginLeft: 10,
lineHeight: 1.2,
display: "-webkit-box",
overflow: "hidden",
wordBreak: "break-word",
textOverflow: "ellipsis",
WebkitLineClamp: 2,
WebkitBoxOrient: "vertical"
}));
var ItemSpecimen = styled9.div(({ theme: theme3 }) => ({
...getBlockBackgroundStyle(theme3),
overflow: "hidden",
height: 40,
width: 40,
display: "flex",
alignItems: "center",
justifyContent: "center",
flex: "none",
"> img, > svg": {
width: 20,
height: 20
}
}));
var Item2 = styled9.div({
display: "inline-flex",
flexDirection: "row",
alignItems: "center",
width: "100%"
});
var List2 = styled9.div({
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(140px, 1fr))",
gridGap: "8px 16px",
gridAutoFlow: "row dense",
gridAutoRows: 50
});
// ../addons/docs/src/blocks/components/TableOfContents.tsx
import React13, { useEffect as useEffect3, useId } from "react";
import { NAVIGATE_URL } from "storybook/internal/core-events";
import { styled as styled10 } from "storybook/theming";
var Aside = styled10.aside(() => ({
width: "10rem",
"@media (max-width: 768px)": {
display: "none"
}
}));
var Nav = styled10.nav(({ theme: theme3 }) => ({
position: "fixed",
bottom: 0,
top: 0,
width: "10rem",
paddingTop: "4rem",
paddingBottom: "2rem",
overflowY: "auto",
fontFamily: theme3.typography.fonts.base,
fontSize: theme3.typography.size.s2,
WebkitFontSmoothing: "antialiased",
MozOsxFontSmoothing: "grayscale",
WebkitTapHighlightColor: "rgba(0, 0, 0, 0)",
WebkitOverflowScrolling: "touch",
"& *": {
boxSizing: "border-box"
},
"& > .toc-wrapper > .toc-list": {
paddingLeft: 0,
borderLeft: `solid 2px ${theme3.color.mediumlight}`,
".toc-list": {
paddingLeft: 0,
borderLeft: `solid 2px ${theme3.color.mediumlight}`,
".toc-list": {
paddingLeft: 0,
borderLeft: `solid 2px ${theme3.color.mediumlight}`
}
}
},
"& .toc-list-item": {
position: "relative",
listStyleType: "none",
marginLeft: 20,
paddingTop: 3,
paddingBottom: 3
},
"& .toc-list-item::before": {
content: '""',
position: "absolute",
height: "100%",
top: 0,
left: 0,
transform: `translateX(calc(-2px - 20px))`,
borderLeft: `solid 2px ${theme3.color.mediumdark}`,
opacity: 0,
transition: "opacity 0.2s"
},
"& .toc-list-item.is-active-li::before": {
opacity: 1
},
"& .toc-list-item > a": {
color: theme3.color.defaultText,
textDecoration: "none"
},
"& .toc-list-item.is-active-li > a": {
fontWeight: 600,
color: theme3.color.secondary,
textDecoration: "none"
}
}));
var Heading = styled10.p(({ theme: theme3 }) => ({
fontWeight: 600,
fontSize: "0.875em",
color: theme3.textColor,
textTransform: "uppercase",
marginBottom: 10
}));
// ../addons/docs/src/blocks/components/ArgsTable/ArgRow.tsx
import React32, { useState as useState11 } from "react";
import { codeCommon as codeCommon3 } from "storybook/internal/components";
// ../node_modules/markdown-to-jsx/dist/index.modern.js
import * as e from "react";
function n() {
return n = Object.assign ? Object.assign.bind() : function(e2) {
for (var n2 = 1; n2 < arguments.length; n2++) {
var r2 = arguments[n2];
for (var t in r2) Object.prototype.hasOwnProperty.call(r2, t) && (e2[t] = r2[t]);
}
return e2;
}, n.apply(this, arguments);
}
__name(n, "n");
var r = ["children", "options"];
var o = ["allowFullScreen", "allowTransparency", "autoComplete", "autoFocus", "autoPlay", "cellPadding", "cellSpacing", "charSet", "classId", "colSpan", "contentEditable", "contextMenu", "crossOrigin", "encType", "formAction", "formEncType", "formMethod", "formNoValidate", "formTarget", "frameBorder", "hrefLang", "inputMode", "keyParams", "keyType", "marginHeight", "marginWidth", "maxLength", "mediaGroup", "minLength", "noValidate", "radioGroup", "readOnly", "rowSpan", "spellCheck", "srcDoc", "srcLang", "srcSet", "tabIndex", "useMap"].reduce((e2, n2) => (e2[n2.toLowerCase()] = n2, e2), { class: "className", for: "htmlFor" });
var a = { amp: "&", apos: "'", gt: ">", lt: "<", nbsp: "\xA0", quot: "\u201C" };
var c = ["style", "script", "pre"];
var i = ["src", "href", "data", "formAction", "srcDoc", "action"];
var u = /([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi;
var l = /mailto:/i;
var s = /\n{2,}$/;
var f = /^(\s*>[\s\S]*?)(?=\n\n|$)/;
var _ = /^ *> ?/gm;
var d = /^(?:\[!([^\]]*)\]\n)?([\s\S]*)/;
var p = /^ {2,}\n/;
var y = /^(?:( *[-*_])){3,} *(?:\n *)+\n/;
var h = /^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/;
var g = /^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/;
var m = /^(`+)((?:\\`|(?!\1)`|[^`])+)\1/;
var k = /^(?:\n *)*\n/;
var x = /\r\n?/g;
var v = /^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/;
var q = /^\[\^([^\]]+)]/;
var $ = /\f/g;
var b = /^---[ \t]*\n(.|\n)*\n---[ \t]*\n/;
var S = /^\s*?\[(x|\s)\]/;
var z = /^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/;
var E = /^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/;
var A = /^([^\n]+)\n *(=|-){3,} *\n/;
var R = /^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i;
var B = /&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi;
var L = /^<!--[\s\S]*?(?:-->)/;
var O = /^(data|aria|x)-[a-z_][a-z\d_.-]*$/;
var j = /^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i;
var C = /^\{.*\}$/;
var I = /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/;
var T = /^<([^ >]+@[^ >]+)>/;
var M = /^<([^ >]+:\/[^ >]+)>/;
var w = /-([a-z])?/gi;
var D = /^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/;
var F = /^[^\n]+(?: \n|\n{2,})/;
var P = /^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/;
var Z = /^!\[([^\]]*)\] ?\[([^\]]*)\]/;
var N = /^\[([^\]]*)\] ?\[([^\]]*)\]/;
var G = /(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/;
var U = /\t/g;
var V = /(^ *\||\| *$)/g;
var H = /^ *:-+: *$/;
var Q = /^ *:-+ *$/;
var W = /^ *-+: *$/;
var J = /* @__PURE__ */ __name((e2) => `(?=[\\s\\S]+?\\1${e2 ? "\\1" : ""})`, "J");
var K = "((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)";
var X = RegExp(`^([*_])\\1${J(1)}${K}\\1\\1(?!\\1)`);
var Y = RegExp(`^([*_])${J(0)}${K}\\1(?!\\1)`);
var ee = RegExp(`^(==)${J(0)}${K}\\1`);
var ne = RegExp(`^(~~)${J(0)}${K}\\1`);
var re = /^(:[a-zA-Z0-9-_]+:)/;
var te = /^\\([^0-9A-Za-z\s])/;
var oe = /\\([^0-9A-Za-z\s])/g;
var ae = /^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/;
var ce = /^\n+/;
var ie = /^([ \t]*)/;
var ue = /(?:^|\n)( *)$/;
var le = "(?:\\d+\\.)";
var se = "(?:[*+-])";
function fe(e2) {
return "( *)(" + (1 === e2 ? le : se) + ") +";
}
__name(fe, "fe");
var _e = fe(1);
var de = fe(2);
function pe(e2) {
return RegExp("^" + (1 === e2 ? _e : de));
}
__name(pe, "pe");
var ye = pe(1);
var he = pe(2);
function ge(e2) {
return RegExp("^" + (1 === e2 ? _e : de) + "[^\\n]*(?:\\n(?!\\1" + (1 === e2 ? le : se) + " )[^\\n]*)*(\\n|$)", "gm");
}
__name(ge, "ge");
var me = ge(1);
var ke = ge(2);
function xe(e2) {
const n2 = 1 === e2 ? le : se;
return RegExp("^( *)(" + n2 + ") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1" + n2 + " (?!" + n2 + " ))\\n*|\\s*\\n*$)");
}
__name(xe, "xe");
var ve = xe(1);
var qe = xe(2);
function $e(e2, n2) {
const r2 = 1 === n2, t = r2 ? ve : qe, o2 = r2 ? me : ke, a2 = r2 ? ye : he;
return { t: /* @__PURE__ */ __name((e3) => a2.test(e3), "t"), o: Ce(function(e3, n3) {
const r3 = ue.exec(n3.prevCapture);
return r3 && (n3.list || !n3.inline && !n3.simple) ? t.exec(e3 = r3[1] + e3) : null;
}), i: 1, u(e3, n3, t2) {
const c2 = r2 ? +e3[2] : void 0, i2 = e3[0].replace(s, "\n").match(o2);
let u2 = false;
return { items: i2.map(function(e4, r3) {
const o3 = a2.exec(e4)[0].length, c3 = RegExp("^ {1," + o3 + "}", "gm"), l2 = e4.replace(c3, "").replace(a2, ""), s2 = r3 === i2.length - 1, f2 = -1 !== l2.indexOf("\n\n") || s2 && u2;
u2 = f2;
const _2 = t2.inline, d2 = t2.list;
let p2;
t2.list = true, f2 ? (t2.inline = false, p2 = ze(l2) + "\n\n") : (t2.inline = true, p2 = ze(l2));
const y2 = n3(p2, t2);
return t2.inline = _2, t2.list = d2, y2;
}), ordered: r2, start: c2 };
}, l: /* @__PURE__ */ __name((n3, r3, t2) => e2(n3.ordered ? "ol" : "ul", { key: t2.key, start: "20" === n3.type ? n3.start : void 0 }, n3.items.map(function(n4, o3) {
return e2("li", { key: o3 }, r3(n4, t2));
})), "l") };
}
__name($e, "$e");
var be = RegExp(`^\\[((?:\\[[^\\[\\]]*(?:\\[[^\\[\\]]*\\][^\\[\\]]*)*\\]|[^\\[\\]])*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['"]([\\s\\S]*?)['"])?\\s*\\)`);
var Se = /^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/;
function ze(e2) {
let n2 = e2.length;
for (; n2 > 0 && e2[n2 - 1] <= " "; ) n2--;
return e2.slice(0, n2);
}
__name(ze, "ze");
function Ee(e2, n2) {
return e2.startsWith(n2);
}
__name(Ee, "Ee");
function Ae(e2, n2, r2) {
if (Array.isArray(r2)) {
for (let n3 = 0; n3 < r2.length; n3++) if (Ee(e2, r2[n3])) return true;
return false;
}
return r2(e2, n2);
}
__name(Ae, "Ae");
function Re(e2) {
return e2.replace(/[ÀÁÂÃÄÅàáâãä忯]/g, "a").replace(/[çÇ]/g, "c").replace(/[ðÐ]/g, "d").replace(/[ÈÉÊËéèêë]/g, "e").replace(/[ÏïÎîÍíÌì]/g, "i").replace(/[Ññ]/g, "n").replace(/[øØœŒÕõÔôÓóÒò]/g, "o").replace(/[ÜüÛûÚúÙù]/g, "u").replace(/[ŸÿÝý]/g, "y").replace(/[^a-z0-9- ]/gi, "").replace(/ /gi, "-").toLowerCase();
}
__name(Re, "Re");
function Be(e2) {
return W.test(e2) ? "right" : H.test(e2) ? "center" : Q.test(e2) ? "left" : null;
}
__name(Be, "Be");
function Le(e2, n2, r2, t) {
const o2 = r2.inTable;
r2.inTable = true;
let a2 = [[]], c2 = "";
function i2() {
if (!c2) return;
const e3 = a2[a2.length - 1];
e3.push.apply(e3, n2(c2, r2)), c2 = "";
}
__name(i2, "i");
return e2.trim().split(/(`[^`]*`|\\\||\|)/).filter(Boolean).forEach((e3, n3, r3) => {
"|" === e3.trim() && (i2(), t) ? 0 !== n3 && n3 !== r3.length - 1 && a2.push([]) : c2 += e3;
}), i2(), r2.inTable = o2, a2;
}
__name(Le, "Le");
function Oe(e2, n2, r2) {
r2.inline = true;
const t = e2[2] ? e2[2].replace(V, "").split("|").map(Be) : [], o2 = e2[3] ? function(e3, n3, r3) {
return e3.trim().split("\n").map(function(e4) {
return Le(e4, n3, r3, true);
});
}(e2[3], n2, r2) : [], a2 = Le(e2[1], n2, r2, !!o2.length);
return r2.inline = false, o2.length ? { align: t, cells: o2, header: a2, type: "25" } : { children: a2, type: "21" };
}
__name(Oe, "Oe");
function je(e2, n2) {
return null == e2.align[n2] ? {} : { textAlign: e2.align[n2] };
}
__name(je, "je");
function Ce(e2) {
return e2.inline = 1, e2;
}
__name(Ce, "Ce");
function Ie(e2) {
return Ce(function(n2, r2) {
return r2.inline ? e2.exec(n2) : null;
});
}
__name(Ie, "Ie");
function Te(e2) {
return Ce(function(n2, r2) {
return r2.inline || r2.simple ? e2.exec(n2) : null;
});
}
__name(Te, "Te");
function Me(e2) {
return function(n2, r2) {
return r2.inline || r2.simple ? null : e2.exec(n2);
};
}
__name(Me, "Me");
function we(e2) {
return Ce(function(n2) {
return e2.exec(n2);
});
}
__name(we, "we");
var De = /(javascript|vbscript|data(?!:image)):/i;
function Fe(e2) {
try {
const n2 = decodeURIComponent(e2).replace(/[^A-Za-z0-9/:]/g, "");
if (De.test(n2)) return null;
} catch (e3) {
return null;
}
return e2;
}
__name(Fe, "Fe");
function Pe(e2) {
return e2 ? e2.replace(oe, "$1") : e2;
}
__name(Pe, "Pe");
function Ze(e2, n2, r2) {
const t = r2.inline || false, o2 = r2.simple || false;
r2.inline = true, r2.simple = true;
const a2 = e2(n2, r2);
return r2.inline = t, r2.simple = o2, a2;
}
__name(Ze, "Ze");
function Ne(e2, n2, r2) {
const t = r2.inline || false, o2 = r2.simple || false;
r2.inline = false, r2.simple = true;
const a2 = e2(n2, r2);
return r2.inline = t, r2.simple = o2, a2;
}
__name(Ne, "Ne");
function Ge(e2, n2, r2) {
const t = r2.inline || false;
r2.inline = false;
const o2 = e2(n2, r2);
return r2.inline = t, o2;
}
__name(Ge, "Ge");
var Ue = /* @__PURE__ */ __name((e2, n2, r2) => ({ children: Ze(n2, e2[2], r2) }), "Ue");
function Ve() {
return {};
}
__name(Ve, "Ve");
function He() {
return null;
}
__name(He, "He");
function Qe(...e2) {
return e2.filter(Boolean).join(" ");
}
__name(Qe, "Qe");
function We(e2, n2, r2) {
let t = e2;
const o2 = n2.split(".");
for (; o2.length && (t = t[o2[0]], void 0 !== t); ) o2.shift();
return t || r2;
}
__name(We, "We");
function Je(r2 = "", t = {}) {
t.overrides = t.overrides || {}, t.namedCodesToUnicode = t.namedCodesToUnicode ? n({}, a, t.namedCodesToUnicode) : a;
const s2 = t.slugify || Re, V2 = t.sanitizer || Fe, H2 = t.createElement || e.createElement, Q2 = [f, h, g, t.enforceAtxHeadings ? E : z, A, D, ve, qe], W2 = [...Q2, F, R, L, j];
function J2(e2, r3, ...o2) {
const a2 = We(t.overrides, e2 + ".props", {});
return H2(function(e3, n2) {
const r4 = We(n2, e3);
return r4 ? "function" == typeof r4 || "object" == typeof r4 && "render" in r4 ? r4 : We(n2, e3 + ".component", e3) : e3;
}(e2, t.overrides), n({}, r3, a2, { className: Qe(null == r3 ? void 0 : r3.className, a2.className) || void 0 }), ...o2);
}
__name(J2, "J");
function K2(e2) {
e2 = e2.replace(b, "");
let n2 = false;
t.forceInline ? n2 = true : t.forceBlock || (n2 = false === G.test(e2));
const r3 = _e2(fe2(n2 ? e2 : ze(e2).replace(ce, "") + "\n\n", { inline: n2 }));
for (; "string" == typeof r3[r3.length - 1] && !r3[r3.length - 1].trim(); ) r3.pop();
if (null === t.wrapper) return r3;
const o2 = t.wrapper || (n2 ? "span" : "div");
let a2;
if (r3.length > 1 || t.forceWrapper) a2 = r3;
else {
if (1 === r3.length) return a2 = r3[0], "string" == typeof a2 ? J2("span", { key: "outer" }, a2) : a2;
a2 = null;
}
return H2(o2, { key: "outer" }, a2);
}
__name(K2, "K");
function oe2(e2, n2) {
if (!n2 || !n2.trim()) return null;
const r3 = n2.match(u);
return r3 ? r3.reduce(function(n3, r4) {
const t2 = r4.indexOf("=");
if (-1 !== t2) {
const a2 = function(e3) {
return -1 !== e3.indexOf("-") && null === e3.match(O) && (e3 = e3.replace(w, function(e4, n4) {
return n4.toUpperCase();
})), e3;
}(r4.slice(0, t2)).trim(), c2 = function(e3) {
const n4 = e3[0];
return ('"' === n4 || "'" === n4) && e3.length >= 2 && e3[e3.length - 1] === n4 ? e3.slice(1, -1) : e3;
}(r4.slice(t2 + 1).trim()), u2 = o[a2] || a2;
if ("ref" === u2) return n3;
const l2 = n3[u2] = function(e3, n4, r5, t3) {
return "style" === n4 ? function(e4) {
const n5 = [];
let r6 = "", t4 = false, o2 = false, a3 = "";
if (!e4) return n5;
for (let c4 = 0; c4 < e4.length; c4++) {
const i2 = e4[c4];
if ('"' !== i2 && "'" !== i2 || t4 || (o2 ? i2 === a3 && (o2 = false, a3 = "") : (o2 = true, a3 = i2)), "(" === i2 && r6.endsWith("url") ? t4 = true : ")" === i2 && t4 && (t4 = false), ";" !== i2 || o2 || t4) r6 += i2;
else {
const e5 = r6.trim();
if (e5) {
const r7 = e5.indexOf(":");
if (r7 > 0) {
const t5 = e5.slice(0, r7).trim(), o3 = e5.slice(r7 + 1).trim();
n5.push([t5, o3]);
}
}
r6 = "";
}
}
const c3 = r6.trim();
if (c3) {
const e5 = c3.indexOf(":");
if (e5 > 0) {
const r7 = c3.slice(0, e5).trim(), t5 = c3.slice(e5 + 1).trim();
n5.push([r7, t5]);
}
}
return n5;
}(r5).reduce(function(n5, [r6, o2]) {
return n5[r6.replace(/(-[a-z])/g, (e4) => e4[1].toUpperCase())] = t3(o2, e3, r6), n5;
}, {}) : -1 !== i.indexOf(n4) ? t3(Pe(r5), e3, n4) : (r5.match(C) && (r5 = Pe(r5.slice(1, r5.length - 1))), "true" === r5 || "false" !== r5 && r5);
}(e2, a2, c2, V2);
"string" == typeof l2 && (R.test(l2) || j.test(l2)) && (n3[u2] = K2(l2.trim()));
} else "style" !== r4 && (n3[o[r4] || r4] = true);
return n3;
}, {}) : null;
}
__name(oe2, "oe");
const ue2 = [], le2 = {}, se2 = { 0: { t: [">"], o: Me(f), i: 1, u(e2, n2, r3) {
const [, t2, o2] = e2[0].replace(_, "").match(d);
return { alert: t2, children: n2(o2, r3) };
}, l(e2, n2, r3) {
const t2 = { key: r3.key };
return e2.alert && (t2.className = "markdown-alert-" + s2(e2.alert.toLowerCase(), Re), e2.children.unshift({ attrs: {}, children: [{ type: "27", text: e2.alert }], noInnerParse: true, type: "11", tag: "header" })), J2("blockquote", t2, n2(e2.children, r3));
} }, 1: { o: we(p), i: 1, u: Ve, l: /* @__PURE__ */ __name((e2, n2, r3) => J2("br", { key: r3.key }), "l") }, 2: { t: /* @__PURE__ */ __name((e2) => {
const n2 = e2[0];
return "-" === n2 || "*" === n2 || "_" === n2;
}, "t"), o: Me(y), i: 1, u: Ve, l: /* @__PURE__ */ __name((e2, n2, r3) => J2("hr", { key: r3.key }), "l") }, 3: { t: [" "], o: Me(g), i: 0, u: /* @__PURE__ */ __name((e2) => ({ lang: void 0, text: Pe(ze(e2[0].replace(/^ {4}/gm, ""))) }), "u"), l: /* @__PURE__ */ __name((e2, r3, t2) => J2("pre", { key: t2.key }, J2("code", n({}, e2.attrs, { className: e2.lang ? "lang-" + e2.lang : "" }), e2.text)), "l") }, 4: { t: ["```", "~~~"], o: Me(h), i: 0, u: /* @__PURE__ */ __name((e2) => ({ attrs: oe2("code", e2[3] || ""), lang: e2[2] || void 0, text: e2[4], type: "3" }), "u") }, 5: { t: ["`"], o: Te(m), i: 3, u: /* @__PURE__ */ __name((e2) => ({ text: Pe(e2[2]) }), "u"), l: /* @__PURE__ */ __name((e2, n2, r3) => J2("code", { key: r3.key }, e2.text), "l") }, 6: { t: ["[^"], o: Me(v), i: 0, u: /* @__PURE__ */ __name((e2) => (ue2.push({ footnote: e2[2], identifier: e2[1] }), {}), "u"), l: He }, 7: { t: ["[^"], o: Ie(q), i: 1, u: /* @__PURE__ */ __name((e2) => ({ target: "#" + s2(e2[1], Re), text: e2[1] }), "u"), l: /* @__PURE__ */ __name((e2, n2, r3) => J2("a", { key: r3.key, href: V2(e2.target, "a", "href") }, J2("sup", { key: r3.key }, e2.text)), "l") }, 8: { t: ["[ ]", "[x]"], o: Ie(S), i: 1, u: /* @__PURE__ */ __name((e2) => ({ completed: "x" === e2[1].toLowerCase() }), "u"), l: /* @__PURE__ */ __name((e2, n2, r3) => J2("input", { checked: e2.completed, key: r3.key, readOnly: true, type: "checkbox" }), "l") }, 9: { t: ["#"], o: Me(t.enforceAtxHeadings ? E : z), i: 1, u: /* @__PURE__ */ __name((e2, n2, r3) => ({ children: Ze(n2, e2[2], r3), id: s2(e2[2], Re), level: e2[1].length }), "u"), l: /* @__PURE__ */ __name((e2, n2, r3) => J2("h" + e2.level, { id: e2.id, key: r3.key }, n2(e2.children, r3)), "l") }, 10: { o: Me(A), i: 0, u: /* @__PURE__ */ __name((e2, n2, r3) => ({ children: Ze(n2, e2[1], r3), level: "=" === e2[2] ? 1 : 2, type: "9" }), "u") }, 11: { t: ["<"], o: we(R), i: 1, u(e2, n2, r3) {
const [, t2] = e2[3].match(ie), o2 = RegExp("^" + t2, "gm"), a2 = e2[3].replace(o2, ""), i2 = (u2 = a2, W2.some((e3) => e3.test(u2)) ? Ge : Ze);
var u2;
const l2 = e2[1].toLowerCase(), s3 = -1 !== c.indexOf(l2), f2 = (s3 ? l2 : e2[1]).trim(), _2 = { attrs: oe2(f2, e2[2]), noInnerParse: s3, tag: f2 };
if (r3.inAnchor = r3.inAnchor || "a" === l2, s3) _2.text = e2[3];
else {
const e3 = r3.inHTML;
r3.inHTML = true, _2.children = i2(n2, a2, r3), r3.inHTML = e3;
}
return r3.inAnchor = false, _2;
}, l: /* @__PURE__ */ __name((e2, r3, t2) => J2(e2.tag, n({ key: t2.key }, e2.attrs), e2.text || (e2.children ? r3(e2.children, t2) : "")), "l") }, 13: { t: ["<"], o: we(j), i: 1, u(e2) {
const n2 = e2[1].trim();
return { attrs: oe2(n2, e2[2] || ""), tag: n2 };
}, l: /* @__PURE__ */ __name((e2, r3, t2) => J2(e2.tag, n({}, e2.attrs, { key: t2.key })), "l") }, 12: { t: ["<!--"], o: we(L), i: 1, u: /* @__PURE__ */ __name(() => ({}), "u"), l: He }, 14: { t: ["!["], o: Te(Se), i: 1, u: /* @__PURE__ */ __name((e2) => ({ alt: Pe(e2[1]), target: Pe(e2[2]), title: Pe(e2[3]) }), "u"), l: /* @__PURE__ */ __name((e2, n2, r3) => J2("img", { key: r3.key, alt: e2.alt || void 0, title: e2.title || void 0, src: V2(e2.target, "img", "src") }), "l") }, 15: { t: ["["], o: Ie(be), i: 3, u: /* @__PURE__ */ __name((e2, n2, r3) => ({ children: Ne(n2, e2[1], r3), target: Pe(e2[2]), title: Pe(e2[3]) }), "u"), l: /* @__PURE__ */ __name((e2, n2, r3) => J2("a", { key: r3.key, href: V2(e2.target, "a", "href"), title: e2.title }, n2(e2.children, r3)), "l") }, 16: { t: ["<"], o: Ie(M), i: 0, u: /* @__PURE__ */ __name((e2) => ({ children: [{ text: e2[1], type: "27" }], target: e2[1], type: "15" }), "u") }, 17: { t: /* @__PURE__ */ __name((e2, n2) => !n2.inAnchor && !t.disableAutoLink && (Ee(e2, "http://") || Ee(e2, "https://")), "t"), o: Ie(I), i: 0, u: /* @__PURE__ */ __name((e2) => ({ children: [{ text: e2[1], type: "27" }], target: e2[1], title: void 0, type: "15" }), "u") }, 18: { t: ["<"], o: Ie(T), i: 0, u(e2) {
let n2 = e2[1], r3 = e2[1];
return l.test(r3) || (r3 = "mailto:" + r3), { children: [{ text: n2.replace("mailto:", ""), type: "27" }], target: r3, type: "15" };
} }, 20: $e(J2, 1), 33: $e(J2, 2), 19: { o: Me(k), i: 3, u: Ve, l: /* @__PURE__ */ __name(() => "\n", "l") }, 21: { o: Ce(function(e2, n2) {
if (n2.inline || n2.simple || n2.inHTML && -1 === e2.indexOf("\n\n") && -1 === n2.prevCapture.indexOf("\n\n")) return null;
let r3 = "";
e2.split("\n").every((e3) => (e3 += "\n", !Q2.some((n3) => n3.test(e3)) && (r3 += e3, !!e3.trim())));
const t2 = ze(r3);
return "" === t2 ? null : [r3, , t2];
}), i: 3, u: Ue, l: /* @__PURE__ */ __name((e2, n2, r3) => J2("p", { key: r3.key }, n2(e2.children, r3)), "l") }, 22: { t: ["["], o: Ie(P), i: 0, u: /* @__PURE__ */ __name((e2) => (le2[e2[1]] = { target: e2[2], title: e2[4] }, {}), "u"), l: He }, 23: { t: ["!["], o: Te(Z), i: 0, u: /* @__PURE__ */ __name((e2) => ({ alt: e2[1] ? Pe(e2[1]) : void 0, ref: e2[2] }), "u"), l: /* @__PURE__ */ __name((e2, n2, r3) => le2[e2.ref] ? J2("img", { key: r3.key, alt: e2.alt, src: V2(le2[e2.ref].target, "img", "src"), title: le2[e2.ref].title }) : null, "l") }, 24: { t: /* @__PURE__ */ __name((e2) => "[" === e2[0] && -1 === e2.indexOf("]("), "t"), o: Ie(N), i: 0, u: /* @__PURE__ */ __name((e2, n2, r3) => ({ children: n2(e2[1], r3), fallbackChildren: e2[0], ref: e2[2] }), "u"), l: /* @__PURE__ */ __name((e2, n2, r3) => le2[e2.ref] ? J2("a", { key: r3.key, href: V2(le2[e2.ref].target, "a", "href"), title: le2[e2.ref].title }, n2(e2.children, r3)) : J2("span", { key: r3.key }, e2.fallbackChildren), "l") }, 25: { t: ["|"], o: Me(D), i: 1, u: Oe, l(e2, n2, r3) {
const t2 = e2;
return J2("table", { key: r3.key }, J2("thead", null, J2("tr", null, t2.header.map(function(e3, o2) {
return J2("th", { key: o2, style: je(t2, o2) }, n2(e3, r3));
}))), J2("tbody", null, t2.cells.map(function(e3, o2) {
return J2("tr", { key: o2 }, e3.map(function(e4, o3) {
return J2("td", { key: o3, style: je(t2, o3) }, n2(e4, r3));
}));
})));
} }, 27: { o: Ce(function(e2, n2) {
let r3;
return Ee(e2, ":") && (r3 = re.exec(e2)), r3 || ae.exec(e2);
}), i: 4, u(e2) {
const n2 = e2[0];
return { text: -1 === n2.indexOf("&") ? n2 : n2.replace(B, (e3, n3) => t.namedCodesToUnicode[n3] || e3) };
}, l: /* @__PURE__ */ __name((e2) => e2.text, "l") }, 28: { t: ["**", "__"], o: Te(X), i: 2, u: /* @__PURE__ */ __name((e2, n2, r3) => ({ children: n2(e2[2], r3) }), "u"), l: /* @__PURE__ */ __name((e2, n2, r3) => J2("strong", { key: r3.key }, n2(e2.children, r3)), "l") }, 29: { t: /* @__PURE__ */ __name((e2) => {
const n2 = e2[0];
return ("*" === n2 || "_" === n2) && e2[1] !== n2;
}, "t"), o: Te(Y), i: 3, u: /* @__PURE__ */ __name((e2, n2, r3) => ({ children: n2(e2[2], r3) }), "u"), l: /* @__PURE__ */ __name((e2, n2, r3) => J2("em", { key: r3.key }, n2(e2.children, r3)), "l") }, 30: { t: ["\\"], o: Te(te), i: 1, u: /* @__PURE__ */ __name((e2) => ({ text: e2[1], type: "27" }), "u") }, 31: { t: ["=="], o: Te(ee), i: 3, u: Ue, l: /* @__PURE__ */ __name((e2, n2, r3) => J2("mark", { key: r3.key }, n2(e2.children, r3)), "l") }, 32: { t: ["~~"], o: Te(ne), i: 3, u: Ue, l: /* @__PURE__ */ __name((e2, n2, r3) => J2("del", { key: r3.key }, n2(e2.children, r3)), "l") } };
true === t.disableParsingRawHTML && (delete se2[11], delete se2[13]);
const fe2 = function(e2) {
var n2 = Object.keys(e2);
function r3(t2, o2) {
var a2 = [];
if (o2.prevCapture = o2.prevCapture || "", t2.trim()) for (; t2; ) for (var c2 = 0; c2 < n2.length; ) {
var i2 = n2[c2], u2 = e2[i2];
if (!u2.t || Ae(t2, o2, u2.t)) {
var l2 = u2.o(t2, o2);
if (l2 && l2[0]) {
t2 = t2.substring(l2[0].length);
var s3 = u2.u(l2, r3, o2);
o2.prevCapture += l2[0], s3.type || (s3.type = i2), a2.push(s3);
break;
}
c2++;
} else c2++;
}
return o2.prevCapture = "", a2;
}
__name(r3, "r");
return n2.sort(function(n3, r4) {
return e2[n3].i - e2[r4].i || (n3 < r4 ? -1 : 1);
}), function(e3, n3) {
return r3(function(e4) {
return e4.replace(x, "\n").replace($, "").replace(U, " ");
}(e3), n3);
};
}(se2), _e2 = (de2 = /* @__PURE__ */ function(e2, n2) {
return function(r3, t2, o2) {
const a2 = e2[r3.type].l;
return n2 ? n2(() => a2(r3, t2, o2), r3, t2, o2) : a2(r3, t2, o2);
};
}(se2, t.renderRule), /* @__PURE__ */ __name(function e2(n2, r3 = {}) {
if (Array.isArray(n2)) {
const t2 = r3.key, o2 = [];
let a2 = false;
for (let t3 = 0; t3 < n2.length; t3++) {
r3.key = t3;
const c2 = e2(n2[t3], r3), i2 = "string" == typeof c2;
i2 && a2 ? o2[o2.length - 1] += c2 : null !== c2 && o2.push(c2), a2 = i2;
}
return r3.key = t2, o2;
}
return de2(n2, e2, r3);
}, "e"));
var de2;
const pe2 = K2(r2);
return ue2.length ? J2("div", null, pe2, J2("footer", { key: "footer" }, ue2.map(function(e2) {
return J2("div", { id: s2(e2.identifier, Re), key: e2.identifier }, e2.identifier, _e2(fe2(e2.footnote, { inline: true })));
}))) : pe2;
}
__name(Je, "Je");
var index_modern_default = /* @__PURE__ */ __name((n2) => {
let { children: t = "", options: o2 } = n2, a2 = function(e2, n3) {
if (null == e2) return {};
var r2, t2, o3 = {}, a3 = Object.keys(e2);
for (t2 = 0; t2 < a3.length; t2++) n3.indexOf(r2 = a3[t2]) >= 0 || (o3[r2] = e2[r2]);
return o3;
}(n2, r);
return e.cloneElement(Je(t, o2), a2);
}, "default");
// ../addons/docs/src/blocks/components/ArgsTable/ArgRow.tsx
import { styled as styled24 } from "storybook/theming";
// ../addons/docs/src/blocks/components/ArgsTable/ArgControl.tsx
import React29, { useCallback as useCallback6, useEffect as useEffect9, useState as useState9 } from "react";
import { Link } from "storybook/internal/components";
// ../addons/docs/src/blocks/controls/index.tsx
import React28, { Suspense, lazy } from "react";
// ../addons/docs/src/blocks/controls/Boolean.tsx
import React14, { useCallback as useCallback2 } from "react";
import { Button } from "storybook/internal/components";
import { styled as styled11 } from "storybook/theming";
var Label2 = styled11.label(({ theme: theme3 }) => ({
lineHeight: "18px",
alignItems: "center",
marginBottom: 8,
display: "inline-block",
position: "relative",
whiteSpace: "nowrap",
background: theme3.boolean.background,
borderRadius: "3em",
padding: 1,
'&[aria-disabled="true"]': {
opacity: 0.5,
input: {
cursor: "not-allowed"
}
},
input: {
appearance: "none",
width: "100%",
height: "100%",
position: "absolute",
left: 0,
top: 0,
margin: 0,
padding: 0,
border: "none",
background: "transparent",
cursor: "pointer",
borderRadius: "3em",
"&:focus": {
outline: "none",
boxShadow: `${theme3.color.secondary} 0 0 0 1px inset !important`
},
"@media (forced-colors: active)": {
"&:focus": {
outline: "1px solid highlight"
}
}
},
span: {
textAlign: "center",
fontSize: theme3.typography.size.s1,
fontWeight: theme3.typography.weight.bold,
lineHeight: "1",
cursor: "pointer",
display: "inline-block",
padding: "7px 15px",
transition: "all 100ms ease-out",
userSelect: "none",
borderRadius: "3em",
color: curriedTransparentize$1(0.5, theme3.color.defaultText),
background: "transparent",
"&:hover": {
boxShadow: `${curriedOpacify$1(0.3, theme3.appBorderColor)} 0 0 0 1px inset`
},
"&:active": {
boxShadow: `${curriedOpacify$1(0.05, theme3.appBorderColor)} 0 0 0 2px inset`,
color: curriedOpacify$1(1, theme3.appBorderColor)
},
"&:first-of-type": {
paddingRight: 8
},
"&:last-of-type": {
paddingLeft: 8
}
},
"input:checked ~ span:last-of-type, input:not(:checked) ~ span:first-of-type": {
background: theme3.boolean.selectedBackground,
boxShadow: theme3.base === "light" ? `${curriedOpacify$1(0.1, theme3.appBorderColor)} 0 0 2px` : `${theme3.appBorderColor} 0 0 0 1px`,
color: theme3.color.defaultText,
padding: "7px 15px",
"@media (forced-colors: active)": {
textDecoration: "underline"
}
}
}));
var parse = /* @__PURE__ */ __name((value2) => value2 === "true", "parse");
var BooleanControl = /* @__PURE__ */ __name(({
name,
value: value2,
onChange,
onBlur,
onFocus,
argType
}) => {
const onSetFalse = useCallback2(() => onChange(false), [onChange]);
const readonly = !!argType?.table?.readonly;
if (value2 === void 0) {
return React14.createElement(
Button,
{
variant: "outline",
size: "medium",
id: getControlSetterButtonId(name),
onClick: onSetFalse,
disabled: readonly
},
"Set boolean"
);
}
const controlId = getControlId(name);
const parsedValue = typeof value2 === "string" ? parse(value2) : value2;
return React14.createElement(Label2, { "aria-disabled": readonly, htmlFor: controlId, "aria-label": name }, React14.createElement(
"input",
{
id: controlId,
type: "checkbox",
onChange: (e2) => onChange(e2.target.checked),
checked: parsedValue,
role: "switch",
disabled: readonly,
...{ name, onBlur, onFocus }
}
), React14.createElement("span", { "aria-hidden": "true" }, "False"), React14.createElement("span", { "aria-hidden": "true" }, "True"));
}, "BooleanControl");
// ../addons/docs/src/blocks/controls/Date.tsx
import React15, { useEffect as useEffect4, useRef as useRef2, useState as useState4 } from "react";
import { Form } from "storybook/internal/components";
import { styled as styled12 } from "storybook/theming";
var parseDate = /* @__PURE__ */ __name((value2) => {
const [year, month, day] = value2.split("-");
const result = /* @__PURE__ */ new Date();
result.setFullYear(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10));
return result;
}, "parseDate");
var parseTime = /* @__PURE__ */ __name((value2) => {
const [hours, minutes] = value2.split(":");
const result = /* @__PURE__ */ new Date();
result.setHours(parseInt(hours, 10));
result.setMinutes(parseInt(minutes, 10));
return result;
}, "parseTime");
var formatDate = /* @__PURE__ */ __name((value2) => {
const date = new Date(value2);
const year = `000${date.getFullYear()}`.slice(-4);
const month = `0${date.getMonth() + 1}`.slice(-2);
const day = `0${date.getDate()}`.slice(-2);
return `${year}-${month}-${day}`;
}, "formatDate");
var formatTime = /* @__PURE__ */ __name((value2) => {
const date = new Date(value2);
const hours = `0${date.getHours()}`.slice(-2);
const minutes = `0${date.getMinutes()}`.slice(-2);
return `${hours}:${minutes}`;
}, "formatTime");
var FormInput = styled12(Form.Input)(({ readOnly }) => ({
opacity: readOnly ? 0.5 : 1
}));
var FlexSpaced = styled12.div(({ theme: theme3 }) => ({
flex: 1,
display: "flex",
input: {
marginLeft: 10,
flex: 1,
height: 32,
// hardcode height bc Chromium bug https://bugs.chromium.org/p/chromium/issues/detail?id=417606
"&::-webkit-calendar-picker-indicator": {
opacity: 0.5,
height: 12,
filter: theme3.base === "light" ? void 0 : "invert(1)"
}
},
"input:first-of-type": {
marginLeft: 0,
flexGrow: 4
},
"input:last-of-type": {
flexGrow: 3
}
}));
var DateControl = /* @__PURE__ */ __name(({ name, value: value2, onChange, onFocus, onBlur, argType }) => {
const [valid, setValid] = useState4(true);
const dateRef = useRef2();
const timeRef = useRef2();
const readonly = !!argType?.table?.readonly;
useEffect4(() => {
if (valid !== false) {
if (dateRef && dateRef.current) {
dateRef.current.value = value2 ? formatDate(value2) : "";
}
if (timeRef && timeRef.current) {
timeRef.current.value = value2 ? formatTime(value2) : "";
}
}
}, [value2]);
const onDateChange = /* @__PURE__ */ __name((e2) => {
if (!e2.target.value) {
return onChange();
}
const parsed = parseDate(e2.target.value);
const result = new Date(value2 ?? "");
result.setFullYear(parsed.getFullYear(), parsed.getMonth(), parsed.getDate());
const time = result.getTime();
if (time) {
onChange(time);
}
setValid(!!time);
}, "onDateChange");
const onTimeChange = /* @__PURE__ */ __name((e2) => {
if (!e2.target.value) {
return onChange();
}
const parsed = parseTime(e2.target.value);
const result = new Date(value2 ?? "");
result.setHours(parsed.getHours());
result.setMinutes(parsed.getMinutes());
const time = result.getTime();
if (time) {
onChange(time);
}
setValid(!!time);
}, "onTimeChange");
const controlId = getControlId(name);
return React15.createElement(FlexSpaced, null, React15.createElement(
FormInput,
{
type: "date",
max: "9999-12-31",
ref: dateRef,
id: `${controlId}-date`,
name: `${controlId}-date`,
readOnly: readonly,
onChange: onDateChange,
...{ onFocus, onBlur }
}
), React15.createElement(
FormInput,
{
type: "time",
id: `${controlId}-time`,
name: `${controlId}-time`,
ref: timeRef,
onChange: onTimeChange,
readOnly: readonly,
...{ onFocus, onBlur }
}
), !valid ? React15.createElement("div", null, "invalid") : null);
}, "DateControl");
// ../addons/docs/src/blocks/controls/Number.tsx
import React16, { useCallback as useCallback3, useEffect as useEffect5, useRef as useRef3, useState as useState5 } from "react";
import { Button as Button2, Form as Form2 } from "storybook/internal/components";
import { styled as styled13 } from "storybook/theming";
var Wrapper4 = styled13.label({
display: "flex"
});
var parse2 = /* @__PURE__ */ __name((value2) => {
const result = parseFloat(value2);
return Number.isNaN(result) ? void 0 : result;
}, "parse");
var FormInput2 = styled13(Form2.Input)(({ readOnly }) => ({
opacity: readOnly ? 0.5 : 1
}));
var NumberControl = /* @__PURE__ */ __name(({
name,
value: value2,
onChange,
min,
max,
step,
onBlur,
onFocus,
argType
}) => {
const [inputValue, setInputValue] = useState5(typeof value2 === "number" ? value2 : "");
const [forceVisible, setForceVisible] = useState5(false);
const [parseError, setParseError] = useState5(null);
const readonly = !!argType?.table?.readonly;
const handleChange = useCallback3(
(event) => {
setInputValue(event.target.value);
const result = parseFloat(event.target.value);
if (Number.isNaN(result)) {
setParseError(new Error(`'${event.target.value}' is not a number`));
} else {
onChange(result);
setParseError(null);
}
},
[onChange, setParseError]
);
const onForceVisible = useCallback3(() => {
setInputValue("0");
onChange(0);
setForceVisible(true);
}, [setForceVisible]);
const htmlElRef = useRef3(null);
useEffect5(() => {
if (forceVisible && htmlElRef.current) {
htmlElRef.current.select();
}
}, [forceVisible]);
useEffect5(() => {
const newInputValue = typeof value2 === "number" ? value2 : "";
if (inputValue !== newInputValue) {
setInputValue(newInputValue);
}
}, [value2]);
if (value2 === void 0) {
return React16.createElement(
Button2,
{
variant: "outline",
size: "medium",
id: getControlSetterButtonId(name),
onClick: onForceVisible,
disabled: readonly
},
"Set number"
);
}
return React16.createElement(Wrapper4, null, React16.createElement(
FormInput2,
{
ref: htmlElRef,
id: getControlId(name),
type: "number",
onChange: handleChange,
size: "flex",
placeholder: "Edit number...",
value: inputValue,
valid: parseError ? "error" : void 0,
autoFocus: forceVisible,
readOnly: readonly,
...{ name, min, max, step, onFocus, onBlur }
}
));
}, "NumberControl");
// ../addons/docs/src/blocks/controls/options/Options.tsx
import React20 from "react";
// ../addons/docs/src/blocks/controls/options/Checkbox.tsx
import React17, { useEffect as useEffect6, useState as useState6 } from "react";
import { logger } from "storybook/internal/client-logger";
import { styled as styled14 } from "storybook/theming";
// ../addons/docs/src/blocks/controls/options/helpers.ts
var selectedKey = /* @__PURE__ */ __name((value2, options) => {
const entry = options && Object.entries(options).find(([_key, val]) => val === value2);
return entry ? entry[0] : void 0;
}, "selectedKey");
var selectedKeys = /* @__PURE__ */ __name((value2, options) => value2 && options ? Object.entries(options).filter((entry) => value2.includes(entry[1])).map((entry) => entry[0]) : [], "selectedKeys");
var selectedValues = /* @__PURE__ */ __name((keys, options) => keys && options && keys.map((key) => options[key]), "selectedValues");
// ../addons/docs/src/blocks/controls/options/Checkbox.tsx
var Wrapper5 = styled14.div(
({ isInline }) => isInline ? {
display: "flex",
flexWrap: "wrap",
alignItems: "flex-start",
label: {
display: "inline-flex",
marginRight: 15
}
} : {
label: {
display: "flex"
}
},
(props) => {
if (props["aria-readonly"] === "true") {
return {
input: {
cursor: "not-allowed"
}
};
}
}
);
var Text = styled14.span({
"[aria-readonly=true] &": {
opacity: 0.5
}
});
var Label3 = styled14.label({
lineHeight: "20px",
alignItems: "center",
marginBottom: 8,
"&:last-child": {
marginBottom: 0
},
input: {
margin: 0,
marginRight: 6
}
});
var CheckboxControl = /* @__PURE__ */ __name(({
name,
options,
value: value2,
onChange,
isInline,
argType
}) => {
if (!options) {
logger.warn(`Checkbox with no options: ${name}`);
return React17.createElement(React17.Fragment, null, "-");
}
const initial = selectedKeys(value2 || [], options);
const [selected, setSelected] = useState6(initial);
const readonly = !!argType?.table?.readonly;
const handleChange = /* @__PURE__ */ __name((e2) => {
const option = e2.target.value;
const updated = [...selected];
if (updated.includes(option)) {
updated.splice(updated.indexOf(option), 1);
} else {
updated.push(option);
}
onChange(selectedValues(updated, options));
setSelected(updated);
}, "handleChange");
useEffect6(() => {
setSelected(selectedKeys(value2 || [], options));
}, [value2]);
const controlId = getControlId(name);
return React17.createElement(Wrapper5, { "aria-readonly": readonly, isInline }, Object.keys(options).map((key, index) => {
const id = `${controlId}-${index}`;
return React17.createElement(Label3, { key: id, htmlFor: id }, React17.createElement(
"input",
{
type: "checkbox",
disabled: readonly,
id,
name: id,
value: key,
onChange: handleChange,
checked: selected?.includes(key)
}
), React17.createElement(Text, null, key));
}));
}, "CheckboxControl");
// ../addons/docs/src/blocks/controls/options/Radio.tsx
import React18 from "react";
import { logger as logger2 } from "storybook/internal/client-logger";
import { styled as styled15 } from "storybook/theming";
var Wrapper6 = styled15.div(
({ isInline }) => isInline ? {
display: "flex",
flexWrap: "wrap",
alignItems: "flex-start",
label: {
display: "inline-flex",
marginRight: 15
}
} : {
label: {
display: "flex"
}
},
(props) => {
if (props["aria-readonly"] === "true") {
return {
input: {
cursor: "not-allowed"
}
};
}
}
);
var Text2 = styled15.span({
"[aria-readonly=true] &": {
opacity: 0.5
}
});
var Label4 = styled15.label({
lineHeight: "20px",
alignItems: "center",
marginBottom: 8,
"&:last-child": {
marginBottom: 0
},
input: {
margin: 0,
marginRight: 6
}
});
var RadioControl = /* @__PURE__ */ __name(({
name,
options,
value: value2,
onChange,
isInline,
argType
}) => {
if (!options) {
logger2.warn(`Radio with no options: ${name}`);
return React18.createElement(React18.Fragment, null, "-");
}
const selection = selectedKey(value2, options);
const controlId = getControlId(name);
const readonly = !!argType?.table?.readonly;
return React18.createElement(Wrapper6, { "aria-readonly": readonly, isInline }, Object.keys(options).map((key, index) => {
const id = `${controlId}-${index}`;
return React18.createElement(Label4, { key: id, htmlFor: id }, React18.createElement(
"input",
{
type: "radio",
id,
name: controlId,
disabled: readonly,
value: key,
onChange: (e2) => onChange(options[e2.currentTarget.value]),
checked: key === selection
}
), React18.createElement(Text2, null, key));
}));
}, "RadioControl");
// ../addons/docs/src/blocks/controls/options/Select.tsx
import React19 from "react";
import { logger as logger3 } from "storybook/internal/client-logger";
import { ChevronSmallDownIcon } from "@storybook/icons";
import { styled as styled16 } from "storybook/theming";
var styleResets = {
// resets
appearance: "none",
border: "0 none",
boxSizing: "inherit",
display: " block",
margin: " 0",
background: "transparent",
padding: 0,
fontSize: "inherit",
position: "relative"
};
var OptionsSelect = styled16.select(styleResets, ({ theme: theme3 }) => ({
boxSizing: "border-box",
position: "relative",
padding: "6px 10px",
width: "100%",
color: theme3.input.color || "inherit",
background: theme3.input.background,
borderRadius: theme3.input.borderRadius,
boxShadow: `${theme3.input.border} 0 0 0 1px inset`,
fontSize: theme3.typography.size.s2 - 1,
lineHeight: "20px",
"&:focus": {
boxShadow: `${theme3.color.secondary} 0 0 0 1px inset`,
outline: "none"
},
"&[disabled]": {
cursor: "not-allowed",
opacity: 0.5
},
"::placeholder": {
color: theme3.textMutedColor
},
"&[multiple]": {
overflow: "auto",
padding: 0,
option: {
display: "block",
padding: "6px 10px",
marginLeft: 1,
marginRight: 1
}
}
}));
var SelectWrapper = styled16.span(({ theme: theme3 }) => ({
display: "inline-block",
lineHeight: "normal",
overflow: "hidden",
position: "relative",
verticalAlign: "top",
width: "100%",
svg: {
position: "absolute",
zIndex: 1,
pointerEvents: "none",
height: "12px",
marginTop: "-6px",
right: "12px",
top: "50%",
fill: theme3.textMutedColor,
path: {
fill: theme3.textMutedColor
}
}
}));
var NO_SELECTION = "Choose option...";
var SingleSelect = /* @__PURE__ */ __name(({ name, value: value2, options, onChange, argType }) => {
const handleChange = /* @__PURE__ */ __name((e2) => {
onChange(options[e2.currentTarget.value]);
}, "handleChange");
const selection = selectedKey(value2, options) || NO_SELECTION;
const controlId = getControlId(name);
const readonly = !!argType?.table?.readonly;
return React19.createElement(SelectWrapper, null, React19.createElement(ChevronSmallDownIcon, null), React19.createElement(OptionsSelect, { disabled: readonly, id: controlId, value: selection, onChange: handleChange }, React19.createElement("option", { key: "no-selection", disabled: true }, NO_SELECTION), Object.keys(options).map((key) => React19.createElement("option", { key, value: key }, key))));
}, "SingleSelect");
var MultiSelect = /* @__PURE__ */ __name(({ name, value: value2, options, onChange, argType }) => {
const handleChange = /* @__PURE__ */ __name((e2) => {
const selection2 = Array.from(e2.currentTarget.options).filter((option) => option.selected).map((option) => option.value);
onChange(selectedValues(selection2, options));
}, "handleChange");
const selection = selectedKeys(value2, options);
const controlId = getControlId(name);
const readonly = !!argType?.table?.readonly;
return React19.createElement(SelectWrapper, null, React19.createElement(
OptionsSelect,
{
disabled: readonly,
id: controlId,
multiple: true,
value: selection,
onChange: handleChange
},
Object.keys(options).map((key) => React19.createElement("option", { key, value: key }, key))
));
}, "MultiSelect");
var SelectControl = /* @__PURE__ */ __name((props) => {
const { name, options } = props;
if (!options) {
logger3.warn(`Select with no options: ${name}`);
return React19.createElement(React19.Fragment, null, "-");
}
return props.isMulti ? React19.createElement(MultiSelect, { ...props }) : React19.createElement(SingleSelect, { ...props });
}, "SelectControl");
// ../addons/docs/src/blocks/controls/options/Options.tsx
var normalizeOptions = /* @__PURE__ */ __name((options, labels) => {
if (Array.isArray(options)) {
return options.reduce((acc, item) => {
acc[labels?.[item] || String(item)] = item;
return acc;
}, {});
}
return options;
}, "normalizeOptions");
var Controls = {
check: CheckboxControl,
"inline-check": CheckboxControl,
radio: RadioControl,
"inline-radio": RadioControl,
select: SelectControl,
"multi-select": SelectControl
};
var OptionsControl = /* @__PURE__ */ __name((props) => {
const { type = "select", labels, argType } = props;
const normalized = {
...props,
argType,
options: argType ? normalizeOptions(argType.options, labels) : {},
isInline: type.includes("inline"),
isMulti: type.includes("multi")
};
const Control = Controls[type];
if (Control) {
return React20.createElement(Control, { ...normalized });
}
throw new Error(`Unknown options type: ${type}`);
}, "OptionsControl");
// ../addons/docs/src/blocks/controls/Object.tsx
import React24, { useCallback as useCallback4, useEffect as useEffect7, useMemo, useRef as useRef4, useState as useState7 } from "react";
import { Button as Button3, Form as Form3, IconButton as IconButton2 } from "storybook/internal/components";
import { AddIcon, EyeCloseIcon, EyeIcon, SubtractIcon } from "@storybook/icons";
import { styled as styled18, useTheme as useTheme2 } from "storybook/theming";
// ../addons/docs/src/blocks/controls/react-editable-json-tree/index.tsx
import React23, { Component as Component3 } from "react";
// ../addons/docs/src/blocks/controls/react-editable-json-tree/JsonNodes.tsx
import React22, { Component as Component2, cloneElement as cloneElement2 } from "react";
// ../addons/docs/src/blocks/controls/react-editable-json-tree/JsonNodeAccordion.tsx
import React21 from "react";
import { styled as styled17 } from "storybook/theming";
var Container = styled17.div(({ theme: theme3 }) => ({
position: "relative",
":hover": {
"& > .rejt-accordion-button::after": {
background: theme3.color.secondary
},
"& > .rejt-accordion-region > :is(.rejt-plus-menu, .rejt-minus-menu)": {
opacity: 1
}
}
}));
var Trigger = styled17.button(({ theme: theme3 }) => ({
padding: 0,
background: "transparent",
border: "none",
marginRight: "3px",
lineHeight: "22px",
color: theme3.color.secondary,
"::after": {
content: '""',
position: "absolute",
top: 0,
display: "block",
width: "100%",
marginLeft: "-1rem",
height: "22px",
background: "transparent",
borderRadius: 4,
transition: "background 0.2s",
opacity: 0.1,
paddingRight: "20px"
},
"::before": {
content: '""',
position: "absolute"
},
'&[aria-expanded="true"]::before': {
left: -10,
top: 10,
borderTop: "3px solid rgba(153,153,153,0.6)",
borderLeft: "3px solid transparent",
borderRight: "3px solid transparent"
},
'&[aria-expanded="false"]::before': {
left: -8,
top: 8,
borderTop: "3px solid transparent",
borderBottom: "3px solid transparent",
borderLeft: "3px solid rgba(153,153,153,0.6)"
}
}));
var Region = styled17.div({
display: "inline"
});
function JsonNodeAccordion({
children,
name,
collapsed,
keyPath,
deep,
...props
}) {
const parentPropertyName = keyPath.at(-1) ?? "root";
const accordionKey = `${parentPropertyName}-${name}-${deep}`;
const ids = {
trigger: `${accordionKey}-trigger`,
region: `${accordionKey}-region`
};
const containerTag = keyPath.length > 0 ? "li" : "div";
return React21.createElement(Container, { as: containerTag }, React21.createElement(
Trigger,
{
type: "button",
"aria-expanded": !collapsed,
id: ids.trigger,
"aria-controls": ids.region,
className: "rejt-accordion-button",
...props
},
name,
" :"
), React21.createElement(
Region,
{
role: "region",
id: ids.region,
"aria-labelledby": ids.trigger,
className: "rejt-accordion-region"
},
children
));
}
__name(JsonNodeAccordion, "JsonNodeAccordion");
// ../addons/docs/src/blocks/controls/react-editable-json-tree/types/dataTypes.ts
var ERROR = "Error";
var OBJECT = "Object";
var ARRAY = "Array";
var STRING = "String";
var NUMBER = "Number";
var BOOLEAN = "Boolean";
var DATE = "Date";
var NULL = "Null";
var UNDEFINED = "Undefined";
var FUNCTION = "Function";
var SYMBOL = "Symbol";
// ../addons/docs/src/blocks/controls/react-editable-json-tree/types/deltaTypes.ts
var ADD_DELTA_TYPE = "ADD_DELTA_TYPE";
var REMOVE_DELTA_TYPE = "REMOVE_DELTA_TYPE";
var UPDATE_DELTA_TYPE = "UPDATE_DELTA_TYPE";
// ../addons/docs/src/blocks/controls/react-editable-json-tree/types/inputUsageTypes.ts
var VALUE = "value";
var KEY = "key";
// ../addons/docs/src/blocks/controls/react-editable-json-tree/utils/objectTypes.ts
function getObjectType(obj) {
if (obj !== null && typeof obj === "object" && !Array.isArray(obj) && typeof obj[Symbol.iterator] === "function") {
return "Iterable";
}
return Object.prototype.toString.call(obj).slice(8, -1);
}
__name(getObjectType, "getObjectType");
function isComponentWillChange(oldValue, newValue) {
const oldType = getObjectType(oldValue);
const newType = getObjectType(newValue);
return (oldType === "Function" || newType === "Function") && newType !== oldType;
}
__name(isComponentWillChange, "isComponentWillChange");
// ../addons/docs/src/blocks/controls/react-editable-json-tree/JsonNodes.tsx
var _JsonAddValue = class _JsonAddValue extends Component2 {
constructor(props) {
super(props);
this.state = {
inputRefKey: null,
inputRefValue: null
};
this.refInputValue = this.refInputValue.bind(this);
this.refInputKey = this.refInputKey.bind(this);
this.onKeydown = this.onKeydown.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
componentDidMount() {
const { inputRefKey, inputRefValue } = this.state;
const { onlyValue } = this.props;
if (inputRefKey && typeof inputRefKey.focus === "function") {
inputRefKey.focus();
}
if (onlyValue && inputRefValue && typeof inputRefValue.focus === "function") {
inputRefValue.focus();
}
}
onKeydown(event) {
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.repeat) {
return;
}
const { inputRefKey, inputRefValue } = this.state;
const { addButtonElement, handleCancel } = this.props;
const isFormFocused = [inputRefKey, inputRefValue, addButtonElement].some(
(elm) => elm === event.target
);
if (!isFormFocused) {
return;
}
if (event.code === "Enter" || event.key === "Enter") {
event.preventDefault();
this.onSubmit();
}
if (event.code === "Escape" || event.key === "Escape") {
event.preventDefault();
handleCancel();
}
}
onSubmit() {
const { handleAdd, onlyValue, onSubmitValueParser, keyPath, deep } = this.props;
const { inputRefKey, inputRefValue } = this.state;
const result = {};
if (!onlyValue) {
if (!inputRefKey.value) {
return;
}
result.key = inputRefKey.value;
}
result.newValue = onSubmitValueParser(false, keyPath, deep, result.key, inputRefValue.value);
handleAdd(result);
}
refInputKey(node) {
this.state.inputRefKey = node;
}
refInputValue(node) {
this.state.inputRefValue = node;
}
render() {
const {
handleCancel,
onlyValue,
addButtonElement,
cancelButtonElement,
inputElementGenerator,
keyPath,
deep
} = this.props;
const addButtonElementLayout = addButtonElement && cloneElement2(addButtonElement, {
onClick: this.onSubmit
});
const cancelButtonElementLayout = cancelButtonElement && cloneElement2(cancelButtonElement, {
onClick: handleCancel
});
const inputElementValue = inputElementGenerator(VALUE, keyPath, deep);
const inputElementValueLayout = cloneElement2(inputElementValue, {
placeholder: "Value",
ref: this.refInputValue,
onKeyDown: this.onKeydown
});
let inputElementKeyLayout = null;
if (!onlyValue) {
const inputElementKey = inputElementGenerator(KEY, keyPath, deep);
inputElementKeyLayout = cloneElement2(inputElementKey, {
placeholder: "Key",
ref: this.refInputKey,
onKeyDown: this.onKeydown
});
}
return React22.createElement("span", { className: "rejt-add-value-node" }, inputElementKeyLayout, inputElementValueLayout, addButtonElementLayout, cancelButtonElementLayout);
}
};
__name(_JsonAddValue, "JsonAddValue");
var JsonAddValue = _JsonAddValue;
JsonAddValue.defaultProps = {
onlyValue: false,
addButtonElement: React22.createElement("button", null, "+"),
cancelButtonElement: React22.createElement("button", null, "c")
};
var _JsonArray = class _JsonArray extends Component2 {
constructor(props) {
super(props);
const keyPath = [...props.keyPath || [], props.name];
this.state = {
data: props.data,
name: props.name,
keyPath: keyPath ?? [],
deep: props.deep ?? 0,
nextDeep: (props.deep ?? 0) + 1,
collapsed: props.isCollapsed(keyPath, props.deep ?? 0, props.data),
addFormVisible: false
};
this.handleCollapseMode = this.handleCollapseMode.bind(this);
this.handleRemoveItem = this.handleRemoveItem.bind(this);
this.handleAddMode = this.handleAddMode.bind(this);
this.handleAddValueAdd = this.handleAddValueAdd.bind(this);
this.handleAddValueCancel = this.handleAddValueCancel.bind(this);
this.handleEditValue = this.handleEditValue.bind(this);
this.onChildUpdate = this.onChildUpdate.bind(this);
this.renderCollapsed = this.renderCollapsed.bind(this);
this.renderNotCollapsed = this.renderNotCollapsed.bind(this);
}
static getDerivedStateFromProps(props, state) {
return props.data !== state.data ? { data: props.data } : null;
}
onChildUpdate(childKey, childData) {
const { data, keyPath = [] } = this.state;
data[childKey] = childData;
this.setState({
data
});
const { onUpdate } = this.props;
const size = keyPath.length;
onUpdate(keyPath[size - 1], data);
}
handleAddMode() {
this.setState({
addFormVisible: true
});
}
handleCollapseMode() {
this.setState((state) => ({
collapsed: !state.collapsed
}));
}
handleRemoveItem(index) {
return () => {
const { beforeRemoveAction, logger: logger5 } = this.props;
const { data, keyPath, nextDeep: deep } = this.state;
const oldValue = data[index];
(beforeRemoveAction || Promise.resolve.bind(Promise))(index, keyPath, deep, oldValue).then(() => {
const deltaUpdateResult = {
keyPath,
deep,
key: index,
oldValue,
type: REMOVE_DELTA_TYPE
};
data.splice(index, 1);
this.setState({ data });
const { onUpdate, onDeltaUpdate } = this.props;
onUpdate(keyPath[keyPath.length - 1], data);
onDeltaUpdate(deltaUpdateResult);
}).catch(logger5.error);
};
}
handleAddValueAdd({ newValue }) {
const { data, keyPath = [], nextDeep: deep } = this.state;
const { beforeAddAction, logger: logger5 } = this.props;
const key = data.length;
(beforeAddAction || Promise.resolve.bind(Promise))(key, keyPath, deep, newValue).then(() => {
data[key] = newValue;
this.setState({
data
});
this.handleAddValueCancel();
const { onUpdate, onDeltaUpdate } = this.props;
onUpdate(keyPath[keyPath.length - 1], data);
onDeltaUpdate({
type: ADD_DELTA_TYPE,
keyPath,
deep,
key,
newValue
});
}).catch(logger5.error);
}
handleAddValueCancel() {
this.setState({
addFormVisible: false
});
}
handleEditValue({ key, value: value2 }) {
return new Promise((resolve, reject) => {
const { beforeUpdateAction } = this.props;
const { data, keyPath, nextDeep: deep } = this.state;
const oldValue = data[key];
(beforeUpdateAction || Promise.resolve.bind(Promise))(key, keyPath, deep, oldValue, value2).then(() => {
data[key] = value2;
this.setState({
data
});
const { onUpdate, onDeltaUpdate } = this.props;
onUpdate(keyPath[keyPath.length - 1], data);
onDeltaUpdate({
type: UPDATE_DELTA_TYPE,
keyPath,
deep,
key,
newValue: value2,
oldValue
});
resolve(void 0);
}).catch(reject);
});
}
renderCollapsed() {
const { name, data, keyPath, deep } = this.state;
const { handleRemove, readOnly, getStyle, dataType, minusMenuElement } = this.props;
const { minus, collapsed } = getStyle(name, data, keyPath, deep, dataType);
const isReadOnly = readOnly(name, data, keyPath, deep, dataType);
const removeItemButton = minusMenuElement && cloneElement2(minusMenuElement, {
onClick: handleRemove,
className: "rejt-minus-menu",
style: minus,
"aria-label": `remove the array '${String(name)}'`
});
return React22.createElement(React22.Fragment, null, React22.createElement("span", { style: collapsed }, "[...] ", data.length, " ", data.length === 1 ? "item" : "items"), !isReadOnly && removeItemButton);
}
renderNotCollapsed() {
const { name, data, keyPath, deep, addFormVisible, nextDeep } = this.state;
const {
isCollapsed,
handleRemove,
onDeltaUpdate,
readOnly,
getStyle,
dataType,
addButtonElement,
cancelButtonElement,
inputElementGenerator,
textareaElementGenerator,
minusMenuElement,
plusMenuElement,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger: logger5,
onSubmitValueParser
} = this.props;
const { minus, plus, delimiter, ul, addForm } = getStyle(name, data, keyPath, deep, dataType);
const isReadOnly = readOnly(name, data, keyPath, deep, dataType);
const addItemButton = plusMenuElement && cloneElement2(plusMenuElement, {
onClick: this.handleAddMode,
className: "rejt-plus-menu",
style: plus,
"aria-label": `add a new item to the '${String(name)}' array`
});
const removeItemButton = minusMenuElement && cloneElement2(minusMenuElement, {
onClick: handleRemove,
className: "rejt-minus-menu",
style: minus,
"aria-label": `remove the array '${String(name)}'`
});
const onlyValue = true;
const startObject = "[";
const endObject = "]";
return React22.createElement(React22.Fragment, null, React22.createElement("span", { className: "rejt-not-collapsed-delimiter", style: delimiter }, startObject), !addFormVisible && addItemButton, React22.createElement("ul", { className: "rejt-not-collapsed-list", style: ul }, data.map((item, index) => React22.createElement(
JsonNode,
{
key: index,
name: index.toString(),
data: item,
keyPath,
deep: nextDeep,
isCollapsed,
handleRemove: this.handleRemoveItem(index),
handleUpdateValue: this.handleEditValue,
onUpdate: this.onChildUpdate,
onDeltaUpdate,
readOnly,
getStyle,
addButtonElement,
cancelButtonElement,
inputElementGenerator,
textareaElementGenerator,
minusMenuElement,
plusMenuElement,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger: logger5,
onSubmitValueParser
}
))), !isReadOnly && addFormVisible && React22.createElement("div", { className: "rejt-add-form", style: addForm }, React22.createElement(
JsonAddValue,
{
handleAdd: this.handleAddValueAdd,
handleCancel: this.handleAddValueCancel,
onlyValue,
addButtonElement,
cancelButtonElement,
inputElementGenerator,
keyPath,
deep,
onSubmitValueParser
}
)), React22.createElement("span", { className: "rejt-not-collapsed-delimiter", style: delimiter }, endObject), !isReadOnly && removeItemButton);
}
render() {
const { name, collapsed, keyPath, deep } = this.state;
const value2 = collapsed ? this.renderCollapsed() : this.renderNotCollapsed();
return React22.createElement(
JsonNodeAccordion,
{
name,
collapsed,
deep,
keyPath,
onClick: this.handleCollapseMode
},
value2
);
}
};
__name(_JsonArray, "JsonArray");
var JsonArray = _JsonArray;
JsonArray.defaultProps = {
keyPath: [],
deep: 0,
minusMenuElement: React22.createElement("span", null, " - "),
plusMenuElement: React22.createElement("span", null, " + ")
};
var _JsonFunctionValue = class _JsonFunctionValue extends Component2 {
constructor(props) {
super(props);
const keyPath = [...props.keyPath || [], props.name];
this.state = {
value: props.value,
name: props.name,
keyPath: keyPath ?? [],
deep: props.deep ?? 0,
editEnabled: false,
inputRef: null
};
this.handleEditMode = this.handleEditMode.bind(this);
this.refInput = this.refInput.bind(this);
this.handleCancelEdit = this.handleCancelEdit.bind(this);
this.handleEdit = this.handleEdit.bind(this);
this.onKeydown = this.onKeydown.bind(this);
}
static getDerivedStateFromProps(props, state) {
return props.value !== state.value ? { value: props.value } : null;
}
componentDidUpdate() {
const { editEnabled, inputRef, name, value: value2, keyPath, deep } = this.state;
const { readOnly, dataType } = this.props;
const readOnlyResult = readOnly(name, value2, keyPath, deep, dataType);
if (editEnabled && !readOnlyResult && typeof inputRef.focus === "function") {
inputRef.focus();
}
}
onKeydown(event) {
const { inputRef } = this.state;
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.repeat || inputRef !== event.target) {
return;
}
if (event.code === "Enter" || event.key === "Enter") {
event.preventDefault();
this.handleEdit();
}
if (event.code === "Escape" || event.key === "Escape") {
event.preventDefault();
this.handleCancelEdit();
}
}
handleEdit() {
const { handleUpdateValue, originalValue, logger: logger5, onSubmitValueParser, keyPath } = this.props;
const { inputRef, name, deep } = this.state;
if (!inputRef) {
return;
}
const newValue = onSubmitValueParser(true, keyPath, deep, name, inputRef.value);
const result = {
value: newValue,
key: name
};
(handleUpdateValue || Promise.resolve.bind(Promise))(result).then(() => {
if (!isComponentWillChange(originalValue, newValue)) {
this.handleCancelEdit();
}
}).catch(logger5.error);
}
handleEditMode() {
this.setState({
editEnabled: true
});
}
refInput(node) {
this.state.inputRef = node;
}
handleCancelEdit() {
this.setState({
editEnabled: false
});
}
render() {
const { name, value: value2, editEnabled, keyPath, deep } = this.state;
const {
handleRemove,
originalValue,
readOnly,
dataType,
getStyle,
textareaElementGenerator,
minusMenuElement,
keyPath: comeFromKeyPath = []
} = this.props;
const style = getStyle(name, originalValue, keyPath, deep, dataType);
let result = null;
let minusElement = null;
const resultOnlyResult = readOnly(name, originalValue, keyPath, deep, dataType);
if (editEnabled && !resultOnlyResult) {
const textareaElement = textareaElementGenerator(
VALUE,
comeFromKeyPath,
deep,
name,
originalValue,
dataType
);
const textareaElementLayout = cloneElement2(textareaElement, {
ref: this.refInput,
defaultValue: value2,
onKeyDown: this.onKeydown
});
result = React22.createElement("span", { className: "rejt-edit-form", style: style.editForm }, textareaElementLayout);
minusElement = null;
} else {
result = React22.createElement(
"span",
{
className: "rejt-value",
style: style.value,
onClick: resultOnlyResult ? void 0 : this.handleEditMode
},
value2
);
const parentPropertyName = comeFromKeyPath.at(-1);
const minusMenuLayout = minusMenuElement && cloneElement2(minusMenuElement, {
onClick: handleRemove,
className: "rejt-minus-menu",
style: style.minus,
"aria-label": `remove the function '${String(name)}'${String(parentPropertyName) ? ` from '${String(parentPropertyName)}'` : ""}`
});
minusElement = resultOnlyResult ? null : minusMenuLayout;
}
return React22.createElement("li", { className: "rejt-value-node", style: style.li }, React22.createElement("span", { className: "rejt-name", style: style.name }, name, " :", " "), result, minusElement);
}
};
__name(_JsonFunctionValue, "JsonFunctionValue");
var JsonFunctionValue = _JsonFunctionValue;
JsonFunctionValue.defaultProps = {
keyPath: [],
deep: 0,
handleUpdateValue: /* @__PURE__ */ __name(() => {
}, "handleUpdateValue"),
cancelButtonElement: React22.createElement("button", null, "c"),
minusMenuElement: React22.createElement("span", null, " - ")
};
var _JsonNode = class _JsonNode extends Component2 {
constructor(props) {
super(props);
this.state = {
data: props.data,
name: props.name,
keyPath: props.keyPath ?? [],
deep: props.deep ?? 0
};
}
static getDerivedStateFromProps(props, state) {
return props.data !== state.data ? { data: props.data } : null;
}
render() {
const { data, name, keyPath, deep } = this.state;
const {
isCollapsed,
handleRemove,
handleUpdateValue,
onUpdate,
onDeltaUpdate,
readOnly,
getStyle,
addButtonElement,
cancelButtonElement,
inputElementGenerator,
textareaElementGenerator,
minusMenuElement,
plusMenuElement,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger: logger5,
onSubmitValueParser
} = this.props;
const readOnlyTrue = /* @__PURE__ */ __name(() => true, "readOnlyTrue");
const dataType = getObjectType(data);
switch (dataType) {
case ERROR:
return React22.createElement(
JsonObject,
{
data,
name,
isCollapsed,
keyPath,
deep,
handleRemove,
onUpdate,
onDeltaUpdate,
readOnly: readOnlyTrue,
dataType,
getStyle,
addButtonElement,
cancelButtonElement,
inputElementGenerator,
textareaElementGenerator,
minusMenuElement,
plusMenuElement,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger: logger5,
onSubmitValueParser
}
);
case OBJECT:
return React22.createElement(
JsonObject,
{
data,
name,
isCollapsed,
keyPath,
deep,
handleRemove,
onUpdate,
onDeltaUpdate,
readOnly,
dataType,
getStyle,
addButtonElement,
cancelButtonElement,
inputElementGenerator,
textareaElementGenerator,
minusMenuElement,
plusMenuElement,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger: logger5,
onSubmitValueParser
}
);
case ARRAY:
return React22.createElement(
JsonArray,
{
data,
name,
isCollapsed,
keyPath,
deep,
handleRemove,
onUpdate,
onDeltaUpdate,
readOnly,
dataType,
getStyle,
addButtonElement,
cancelButtonElement,
inputElementGenerator,
textareaElementGenerator,
minusMenuElement,
plusMenuElement,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger: logger5,
onSubmitValueParser
}
);
case STRING:
return React22.createElement(
JsonValue,
{
name,
value: `"${data}"`,
originalValue: data,
keyPath,
deep,
handleRemove,
handleUpdateValue,
readOnly,
dataType,
getStyle,
cancelButtonElement,
inputElementGenerator,
minusMenuElement,
logger: logger5,
onSubmitValueParser
}
);
case NUMBER:
return React22.createElement(
JsonValue,
{
name,
value: data,
originalValue: data,
keyPath,
deep,
handleRemove,
handleUpdateValue,
readOnly,
dataType,
getStyle,
cancelButtonElement,
inputElementGenerator,
minusMenuElement,
logger: logger5,
onSubmitValueParser
}
);
case BOOLEAN:
return React22.createElement(
JsonValue,
{
name,
value: data ? "true" : "false",
originalValue: data,
keyPath,
deep,
handleRemove,
handleUpdateValue,
readOnly,
dataType,
getStyle,
cancelButtonElement,
inputElementGenerator,
minusMenuElement,
logger: logger5,
onSubmitValueParser
}
);
case DATE:
return React22.createElement(
JsonValue,
{
name,
value: data.toISOString(),
originalValue: data,
keyPath,
deep,
handleRemove,
handleUpdateValue,
readOnly: readOnlyTrue,
dataType,
getStyle,
cancelButtonElement,
inputElementGenerator,
minusMenuElement,
logger: logger5,
onSubmitValueParser
}
);
case NULL:
return React22.createElement(
JsonValue,
{
name,
value: "null",
originalValue: "null",
keyPath,
deep,
handleRemove,
handleUpdateValue,
readOnly,
dataType,
getStyle,
cancelButtonElement,
inputElementGenerator,
minusMenuElement,
logger: logger5,
onSubmitValueParser
}
);
case UNDEFINED:
return React22.createElement(
JsonValue,
{
name,
value: "undefined",
originalValue: "undefined",
keyPath,
deep,
handleRemove,
handleUpdateValue,
readOnly,
dataType,
getStyle,
cancelButtonElement,
inputElementGenerator,
minusMenuElement,
logger: logger5,
onSubmitValueParser
}
);
case FUNCTION:
return React22.createElement(
JsonFunctionValue,
{
name,
value: data.toString(),
originalValue: data,
keyPath,
deep,
handleRemove,
handleUpdateValue,
readOnly,
dataType,
getStyle,
cancelButtonElement,
textareaElementGenerator,
minusMenuElement,
logger: logger5,
onSubmitValueParser
}
);
case SYMBOL:
return React22.createElement(
JsonValue,
{
name,
value: data.toString(),
originalValue: data,
keyPath,
deep,
handleRemove,
handleUpdateValue,
readOnly: readOnlyTrue,
dataType,
getStyle,
cancelButtonElement,
inputElementGenerator,
minusMenuElement,
logger: logger5,
onSubmitValueParser
}
);
default:
return null;
}
}
};
__name(_JsonNode, "JsonNode");
var JsonNode = _JsonNode;
JsonNode.defaultProps = {
keyPath: [],
deep: 0
};
var _JsonObject = class _JsonObject extends Component2 {
constructor(props) {
super(props);
const keyPath = props.deep === -1 ? [] : [...props.keyPath || [], props.name];
this.state = {
name: props.name,
data: props.data,
keyPath: keyPath ?? [],
deep: props.deep ?? 0,
nextDeep: (props.deep ?? 0) + 1,
collapsed: props.isCollapsed(keyPath, props.deep ?? 0, props.data),
addFormVisible: false
};
this.handleCollapseMode = this.handleCollapseMode.bind(this);
this.handleRemoveValue = this.handleRemoveValue.bind(this);
this.handleAddMode = this.handleAddMode.bind(this);
this.handleAddValueAdd = this.handleAddValueAdd.bind(this);
this.handleAddValueCancel = this.handleAddValueCancel.bind(this);
this.handleEditValue = this.handleEditValue.bind(this);
this.onChildUpdate = this.onChildUpdate.bind(this);
this.renderCollapsed = this.renderCollapsed.bind(this);
this.renderNotCollapsed = this.renderNotCollapsed.bind(this);
}
static getDerivedStateFromProps(props, state) {
return props.data !== state.data ? { data: props.data } : null;
}
onChildUpdate(childKey, childData) {
const { data, keyPath = [] } = this.state;
data[childKey] = childData;
this.setState({
data
});
const { onUpdate } = this.props;
const size = keyPath.length;
onUpdate(keyPath[size - 1], data);
}
handleAddMode() {
this.setState({
addFormVisible: true
});
}
handleAddValueCancel() {
this.setState({
addFormVisible: false
});
}
handleAddValueAdd({ key, newValue }) {
const { data, keyPath = [], nextDeep: deep } = this.state;
const { beforeAddAction, logger: logger5 } = this.props;
(beforeAddAction || Promise.resolve.bind(Promise))(key, keyPath, deep, newValue).then(() => {
data[key] = newValue;
this.setState({
data
});
this.handleAddValueCancel();
const { onUpdate, onDeltaUpdate } = this.props;
onUpdate(keyPath[keyPath.length - 1], data);
onDeltaUpdate({
type: ADD_DELTA_TYPE,
keyPath,
deep,
key,
newValue
});
}).catch(logger5.error);
}
handleRemoveValue(key) {
return () => {
const { beforeRemoveAction, logger: logger5 } = this.props;
const { data, keyPath = [], nextDeep: deep } = this.state;
const oldValue = data[key];
(beforeRemoveAction || Promise.resolve.bind(Promise))(key, keyPath, deep, oldValue).then(() => {
const deltaUpdateResult = {
keyPath,
deep,
key,
oldValue,
type: REMOVE_DELTA_TYPE
};
delete data[key];
this.setState({ data });
const { onUpdate, onDeltaUpdate } = this.props;
onUpdate(keyPath[keyPath.length - 1], data);
onDeltaUpdate(deltaUpdateResult);
}).catch(logger5.error);
};
}
handleCollapseMode() {
this.setState((state) => ({
collapsed: !state.collapsed
}));
}
handleEditValue({ key, value: value2 }) {
return new Promise((resolve, reject) => {
const { beforeUpdateAction } = this.props;
const { data, keyPath = [], nextDeep: deep } = this.state;
const oldValue = data[key];
(beforeUpdateAction || Promise.resolve.bind(Promise))(key, keyPath, deep, oldValue, value2).then(() => {
data[key] = value2;
this.setState({
data
});
const { onUpdate, onDeltaUpdate } = this.props;
onUpdate(keyPath[keyPath.length - 1], data);
onDeltaUpdate({
type: UPDATE_DELTA_TYPE,
keyPath,
deep,
key,
newValue: value2,
oldValue
});
resolve();
}).catch(reject);
});
}
renderCollapsed() {
const { name, keyPath, deep, data } = this.state;
const { handleRemove, readOnly, dataType, getStyle, minusMenuElement } = this.props;
const { minus, collapsed } = getStyle(name, data, keyPath, deep, dataType);
const keyList = Object.getOwnPropertyNames(data);
const isReadOnly = readOnly(name, data, keyPath, deep, dataType);
const removeItemButton = minusMenuElement && cloneElement2(minusMenuElement, {
onClick: handleRemove,
className: "rejt-minus-menu",
style: minus,
"aria-label": `remove the object '${String(name)}'`
});
return React22.createElement(React22.Fragment, null, React22.createElement("span", { style: collapsed }, "{...}", " ", keyList.length, " ", keyList.length === 1 ? "key" : "keys"), !isReadOnly && removeItemButton);
}
renderNotCollapsed() {
const { name, data, keyPath, deep, nextDeep, addFormVisible } = this.state;
const {
isCollapsed,
handleRemove,
onDeltaUpdate,
readOnly,
getStyle,
dataType,
addButtonElement,
cancelButtonElement,
inputElementGenerator,
textareaElementGenerator,
minusMenuElement,
plusMenuElement,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger: logger5,
onSubmitValueParser
} = this.props;
const { minus, plus, addForm, ul, delimiter } = getStyle(name, data, keyPath, deep, dataType);
const keyList = Object.getOwnPropertyNames(data);
const isReadOnly = readOnly(name, data, keyPath, deep, dataType);
const addItemButton = plusMenuElement && cloneElement2(plusMenuElement, {
onClick: this.handleAddMode,
className: "rejt-plus-menu",
style: plus,
"aria-label": `add a new property to the object '${String(name)}'`
});
const removeItemButton = minusMenuElement && cloneElement2(minusMenuElement, {
onClick: handleRemove,
className: "rejt-minus-menu",
style: minus,
"aria-label": `remove the object '${String(name)}'`
});
const list = keyList.map((key) => React22.createElement(
JsonNode,
{
key,
name: key,
data: data[key],
keyPath,
deep: nextDeep,
isCollapsed,
handleRemove: this.handleRemoveValue(key),
handleUpdateValue: this.handleEditValue,
onUpdate: this.onChildUpdate,
onDeltaUpdate,
readOnly,
getStyle,
addButtonElement,
cancelButtonElement,
inputElementGenerator,
textareaElementGenerator,
minusMenuElement,
plusMenuElement,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger: logger5,
onSubmitValueParser
}
));
const startObject = "{";
const endObject = "}";
return React22.createElement(React22.Fragment, null, React22.createElement("span", { className: "rejt-not-collapsed-delimiter", style: delimiter }, startObject), !isReadOnly && addItemButton, React22.createElement("ul", { className: "rejt-not-collapsed-list", style: ul }, list), !isReadOnly && addFormVisible && React22.createElement("div", { className: "rejt-add-form", style: addForm }, React22.createElement(
JsonAddValue,
{
handleAdd: this.handleAddValueAdd,
handleCancel: this.handleAddValueCancel,
addButtonElement,
cancelButtonElement,
inputElementGenerator,
keyPath,
deep,
onSubmitValueParser
}
)), React22.createElement("span", { className: "rejt-not-collapsed-delimiter", style: delimiter }, endObject), !isReadOnly && removeItemButton);
}
render() {
const { name, collapsed, keyPath, deep = 0 } = this.state;
const value2 = collapsed ? this.renderCollapsed() : this.renderNotCollapsed();
return React22.createElement(
JsonNodeAccordion,
{
name,
collapsed,
deep,
keyPath,
onClick: this.handleCollapseMode
},
value2
);
}
};
__name(_JsonObject, "JsonObject");
var JsonObject = _JsonObject;
JsonObject.defaultProps = {
keyPath: [],
deep: 0,
minusMenuElement: React22.createElement("span", null, " - "),
plusMenuElement: React22.createElement("span", null, " + ")
};
var _JsonValue = class _JsonValue extends Component2 {
constructor(props) {
super(props);
const keyPath = [...props.keyPath || [], props.name];
this.state = {
value: props.value,
name: props.name,
keyPath: keyPath ?? [],
deep: props.deep ?? 0,
editEnabled: false,
inputRef: null
};
this.handleEditMode = this.handleEditMode.bind(this);
this.refInput = this.refInput.bind(this);
this.handleCancelEdit = this.handleCancelEdit.bind(this);
this.handleEdit = this.handleEdit.bind(this);
this.onKeydown = this.onKeydown.bind(this);
}
static getDerivedStateFromProps(props, state) {
return props.value !== state.value ? { value: props.value } : null;
}
componentDidUpdate() {
const { editEnabled, inputRef, name, value: value2, keyPath, deep } = this.state;
const { readOnly, dataType } = this.props;
const isReadOnly = readOnly(name, value2, keyPath, deep, dataType);
if (editEnabled && !isReadOnly && typeof inputRef.focus === "function") {
inputRef.focus();
}
}
onKeydown(event) {
const { inputRef } = this.state;
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.repeat || inputRef !== event.target) {
return;
}
if (event.code === "Enter" || event.key === "Enter") {
event.preventDefault();
this.handleEdit();
}
if (event.code === "Escape" || event.key === "Escape") {
event.preventDefault();
this.handleCancelEdit();
}
}
handleEdit() {
const { handleUpdateValue, originalValue, logger: logger5, onSubmitValueParser, keyPath } = this.props;
const { inputRef, name, deep } = this.state;
if (!inputRef) {
return;
}
const newValue = onSubmitValueParser(true, keyPath, deep, name, inputRef.value);
const result = {
value: newValue,
key: name
};
(handleUpdateValue || Promise.resolve.bind(Promise))(result).then(() => {
if (!isComponentWillChange(originalValue, newValue)) {
this.handleCancelEdit();
}
}).catch(logger5.error);
}
handleEditMode() {
this.setState({
editEnabled: true
});
}
refInput(node) {
this.state.inputRef = node;
}
handleCancelEdit() {
this.setState({
editEnabled: false
});
}
render() {
const { name, value: value2, editEnabled, keyPath, deep } = this.state;
const {
handleRemove,
originalValue,
readOnly,
dataType,
getStyle,
inputElementGenerator,
minusMenuElement,
keyPath: comeFromKeyPath
} = this.props;
const style = getStyle(name, originalValue, keyPath, deep, dataType);
const isReadOnly = readOnly(name, originalValue, keyPath, deep, dataType);
const isEditing = editEnabled && !isReadOnly;
const inputElement = inputElementGenerator(
VALUE,
comeFromKeyPath,
deep,
name,
originalValue,
dataType
);
const inputElementLayout = cloneElement2(inputElement, {
ref: this.refInput,
defaultValue: JSON.stringify(originalValue),
onKeyDown: this.onKeydown
});
const parentPropertyName = keyPath.at(-2);
const minusMenuLayout = minusMenuElement && cloneElement2(minusMenuElement, {
onClick: handleRemove,
className: "rejt-minus-menu",
style: style.minus,
"aria-label": `remove the property '${String(name)}' with value '${String(originalValue)}'${String(parentPropertyName) ? ` from '${String(parentPropertyName)}'` : ""}`
});
return React22.createElement("li", { className: "rejt-value-node", style: style.li }, React22.createElement("span", { className: "rejt-name", style: style.name }, name, " : "), isEditing ? React22.createElement("span", { className: "rejt-edit-form", style: style.editForm }, inputElementLayout) : React22.createElement(
"span",
{
className: "rejt-value",
style: style.value,
onClick: isReadOnly ? void 0 : this.handleEditMode
},
String(value2)
), !isReadOnly && !isEditing && minusMenuLayout);
}
};
__name(_JsonValue, "JsonValue");
var JsonValue = _JsonValue;
JsonValue.defaultProps = {
keyPath: [],
deep: 0,
handleUpdateValue: /* @__PURE__ */ __name(() => Promise.resolve(), "handleUpdateValue"),
cancelButtonElement: React22.createElement("button", null, "c"),
minusMenuElement: React22.createElement("span", null, " - ")
};
// ../addons/docs/src/blocks/controls/react-editable-json-tree/utils/parse.ts
function parse3(string) {
let result = string;
if (result.indexOf("function") === 0) {
return (0, eval)(`(${result})`);
}
try {
result = JSON.parse(string);
} catch (e2) {
}
return result;
}
__name(parse3, "parse");
// ../addons/docs/src/blocks/controls/react-editable-json-tree/utils/styles.ts
var object = {
minus: {
color: "red"
},
plus: {
color: "green"
},
collapsed: {
color: "grey"
},
delimiter: {},
ul: {
padding: "0px",
margin: "0 0 0 25px",
listStyle: "none"
},
name: {
color: "#2287CD"
},
addForm: {}
};
var array = {
minus: {
color: "red"
},
plus: {
color: "green"
},
collapsed: {
color: "grey"
},
delimiter: {},
ul: {
padding: "0px",
margin: "0 0 0 25px",
listStyle: "none"
},
name: {
color: "#2287CD"
},
addForm: {}
};
var value = {
minus: {
color: "red"
},
editForm: {},
value: {
color: "#7bba3d"
},
li: {
minHeight: "22px",
lineHeight: "22px",
outline: "0px"
},
name: {
color: "#2287CD"
}
};
// ../addons/docs/src/blocks/controls/react-editable-json-tree/index.tsx
var _JsonTree = class _JsonTree extends Component3 {
constructor(props) {
super(props);
this.state = {
data: props.data,
rootName: props.rootName
};
this.onUpdate = this.onUpdate.bind(this);
this.removeRoot = this.removeRoot.bind(this);
}
static getDerivedStateFromProps(props, state) {
if (props.data !== state.data || props.rootName !== state.rootName) {
return {
data: props.data,
rootName: props.rootName
};
}
return null;
}
onUpdate(key, data) {
this.setState({ data });
this.props.onFullyUpdate?.(data);
}
removeRoot() {
this.onUpdate(null, null);
}
render() {
const { data, rootName } = this.state;
const {
isCollapsed,
onDeltaUpdate,
readOnly,
getStyle,
addButtonElement,
cancelButtonElement,
inputElement,
textareaElement,
minusMenuElement,
plusMenuElement,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger: logger5,
onSubmitValueParser,
fallback = null
} = this.props;
const dataType = getObjectType(data);
let readOnlyFunction = readOnly;
if (getObjectType(readOnly) === "Boolean") {
readOnlyFunction = /* @__PURE__ */ __name(() => readOnly, "readOnlyFunction");
}
let inputElementFunction = inputElement;
if (inputElement && getObjectType(inputElement) !== "Function") {
inputElementFunction = /* @__PURE__ */ __name(() => inputElement, "inputElementFunction");
}
let textareaElementFunction = textareaElement;
if (textareaElement && getObjectType(textareaElement) !== "Function") {
textareaElementFunction = /* @__PURE__ */ __name(() => textareaElement, "textareaElementFunction");
}
if (dataType === "Object" || dataType === "Array") {
return React23.createElement("div", { className: "rejt-tree" }, React23.createElement(
JsonNode,
{
data,
name: rootName || "root",
deep: -1,
isCollapsed: isCollapsed ?? (() => false),
onUpdate: this.onUpdate,
onDeltaUpdate: onDeltaUpdate ?? (() => {
}),
readOnly: readOnlyFunction,
getStyle: getStyle ?? (() => ({})),
addButtonElement,
cancelButtonElement,
inputElementGenerator: inputElementFunction,
textareaElementGenerator: textareaElementFunction,
minusMenuElement,
plusMenuElement,
handleRemove: this.removeRoot,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger: logger5 ?? {},
onSubmitValueParser: onSubmitValueParser ?? ((val) => val)
}
));
}
return fallback;
}
};
__name(_JsonTree, "JsonTree");
var JsonTree = _JsonTree;
JsonTree.defaultProps = {
rootName: "root",
isCollapsed: /* @__PURE__ */ __name((keyPath, deep) => deep !== -1, "isCollapsed"),
getStyle: /* @__PURE__ */ __name((keyName, data, keyPath, deep, dataType) => {
switch (dataType) {
case "Object":
case "Error":
return object;
case "Array":
return array;
default:
return value;
}
}, "getStyle"),
readOnly: /* @__PURE__ */ __name(() => false, "readOnly"),
onFullyUpdate: /* @__PURE__ */ __name(() => {
}, "onFullyUpdate"),
onDeltaUpdate: /* @__PURE__ */ __name(() => {
}, "onDeltaUpdate"),
beforeRemoveAction: /* @__PURE__ */ __name(() => Promise.resolve(), "beforeRemoveAction"),
beforeAddAction: /* @__PURE__ */ __name(() => Promise.resolve(), "beforeAddAction"),
beforeUpdateAction: /* @__PURE__ */ __name(() => Promise.resolve(), "beforeUpdateAction"),
logger: { error: /* @__PURE__ */ __name(() => {
}, "error") },
onSubmitValueParser: /* @__PURE__ */ __name((isEditMode, keyPath, deep, name, rawValue) => parse3(rawValue), "onSubmitValueParser"),
inputElement: /* @__PURE__ */ __name(() => React23.createElement("input", null), "inputElement"),
textareaElement: /* @__PURE__ */ __name(() => React23.createElement("textarea", null), "textareaElement"),
fallback: null
};
// ../addons/docs/src/blocks/controls/Object.tsx
var { window: globalWindow2 } = globalThis;
var Wrapper7 = styled18.div(({ theme: theme3 }) => ({
position: "relative",
display: "flex",
'&[aria-readonly="true"]': {
opacity: 0.5
},
".rejt-tree": {
marginLeft: "1rem",
fontSize: "13px",
listStyleType: "none"
},
".rejt-value-node:hover": {
"& > button": {
opacity: 1
}
},
".rejt-add-form": {
marginLeft: 10
},
".rejt-add-value-node": {
display: "inline-flex",
alignItems: "center"
},
".rejt-name": {
lineHeight: "22px"
},
".rejt-not-collapsed-delimiter": {
lineHeight: "22px"
},
".rejt-value": {
display: "inline-block",
border: "1px solid transparent",
borderRadius: 4,
margin: "1px 0",
padding: "0 4px",
cursor: "text",
color: theme3.color.defaultText
},
".rejt-value-node:hover > .rejt-value": {
background: theme3.color.lighter,
borderColor: theme3.appBorderColor
}
}));
var ButtonInline = styled18.button(({ theme: theme3, primary }) => ({
border: 0,
height: 20,
margin: 1,
borderRadius: 4,
background: primary ? theme3.color.secondary : "transparent",
color: primary ? theme3.color.lightest : theme3.color.dark,
fontWeight: primary ? "bold" : "normal",
cursor: "pointer"
}));
var ActionButton = styled18.button(({ theme: theme3 }) => ({
background: "none",
border: 0,
display: "inline-flex",
verticalAlign: "middle",
padding: 3,
marginLeft: 5,
color: theme3.textMutedColor,
opacity: 0,
transition: "opacity 0.2s",
cursor: "pointer",
position: "relative",
svg: {
width: 9,
height: 9
},
":disabled": {
cursor: "not-allowed"
},
":hover, :focus-visible": {
opacity: 1
},
"&:hover:not(:disabled), &:focus-visible:not(:disabled)": {
"&.rejt-plus-menu": {
color: theme3.color.ancillary
},
"&.rejt-minus-menu": {
color: theme3.color.negative
}
}
}));
var Input = styled18.input(({ theme: theme3, placeholder }) => ({
outline: 0,
margin: placeholder ? 1 : "1px 0",
padding: "3px 4px",
color: theme3.color.defaultText,
background: theme3.background.app,
border: `1px solid ${theme3.appBorderColor}`,
borderRadius: 4,
lineHeight: "14px",
width: placeholder === "Key" ? 80 : 120,
"&:focus": {
border: `1px solid ${theme3.color.secondary}`
}
}));
var RawButton = styled18(IconButton2)(({ theme: theme3 }) => ({
position: "absolute",
zIndex: 2,
top: 2,
right: 2,
height: 21,
padding: "0 3px",
background: theme3.background.bar,
border: `1px solid ${theme3.appBorderColor}`,
borderRadius: 3,
color: theme3.textMutedColor,
fontSize: "9px",
fontWeight: "bold",
textDecoration: "none",
span: {
marginLeft: 3,
marginTop: 1
}
}));
var RawInput = styled18(Form3.Textarea)(({ theme: theme3 }) => ({
flex: 1,
padding: "7px 6px",
fontFamily: theme3.typography.fonts.mono,
fontSize: "12px",
lineHeight: "18px",
"&::placeholder": {
fontFamily: theme3.typography.fonts.base,
fontSize: "13px"
},
"&:placeholder-shown": {
padding: "7px 10px"
}
}));
var ENTER_EVENT = {
bubbles: true,
cancelable: true,
key: "Enter",
code: "Enter",
keyCode: 13
};
var dispatchEnterKey = /* @__PURE__ */ __name((event) => {
event.currentTarget.dispatchEvent(new globalWindow2.KeyboardEvent("keydown", ENTER_EVENT));
}, "dispatchEnterKey");
var selectValue = /* @__PURE__ */ __name((event) => {
event.currentTarget.select();
}, "selectValue");
var getCustomStyleFunction = /* @__PURE__ */ __name((theme3) => () => ({
name: {
color: theme3.color.secondary
},
collapsed: {
color: theme3.color.dark
},
ul: {
listStyle: "none",
margin: "0 0 0 1rem",
padding: 0
},
li: {
outline: 0
}
}), "getCustomStyleFunction");
var ObjectControl = /* @__PURE__ */ __name(({ name, value: value2, onChange, argType }) => {
const theme3 = useTheme2();
const data = useMemo(() => value2 && cloneDeep(value2), [value2]);
const hasData = data !== null && data !== void 0;
const [showRaw, setShowRaw] = useState7(!hasData);
const [parseError, setParseError] = useState7(null);
const readonly = !!argType?.table?.readonly;
const updateRaw = useCallback4(
(raw) => {
try {
if (raw) {
onChange(JSON.parse(raw));
}
setParseError(null);
} catch (e2) {
setParseError(e2);
}
},
[onChange]
);
const [forceVisible, setForceVisible] = useState7(false);
const onForceVisible = useCallback4(() => {
onChange({});
setForceVisible(true);
}, [setForceVisible]);
const htmlElRef = useRef4(null);
useEffect7(() => {
if (forceVisible && htmlElRef.current) {
htmlElRef.current.select();
}
}, [forceVisible]);
if (!hasData) {
return React24.createElement(Button3, { disabled: readonly, id: getControlSetterButtonId(name), onClick: onForceVisible }, "Set object");
}
const rawJSONForm = React24.createElement(
RawInput,
{
ref: htmlElRef,
id: getControlId(name),
name,
defaultValue: value2 === null ? "" : JSON.stringify(value2, null, 2),
onBlur: (event) => updateRaw(event.target.value),
placeholder: "Edit JSON string...",
autoFocus: forceVisible,
valid: parseError ? "error" : void 0,
readOnly: readonly
}
);
const isObjectOrArray = Array.isArray(value2) || typeof value2 === "object" && value2?.constructor === Object;
return React24.createElement(Wrapper7, { "aria-readonly": readonly }, isObjectOrArray && React24.createElement(
RawButton,
{
role: "switch",
"aria-checked": showRaw,
"aria-label": `Edit the ${name} properties in text format`,
onClick: (e2) => {
e2.preventDefault();
setShowRaw((isRaw) => !isRaw);
}
},
showRaw ? React24.createElement(EyeCloseIcon, null) : React24.createElement(EyeIcon, null),
React24.createElement("span", null, "RAW")
), !showRaw ? React24.createElement(
JsonTree,
{
readOnly: readonly || !isObjectOrArray,
isCollapsed: isObjectOrArray ? (
/* default value */
void 0
) : () => true,
data,
rootName: name,
onFullyUpdate: onChange,
getStyle: getCustomStyleFunction(theme3),
cancelButtonElement: React24.createElement(ButtonInline, { type: "button" }, "Cancel"),
addButtonElement: React24.createElement(ButtonInline, { type: "submit", primary: true }, "Save"),
plusMenuElement: React24.createElement(ActionButton, { type: "button" }, React24.createElement(AddIcon, null)),
minusMenuElement: React24.createElement(ActionButton, { type: "button" }, React24.createElement(SubtractIcon, null)),
inputElement: (_2, __, ___, key) => key ? React24.createElement(Input, { onFocus: selectValue, onBlur: dispatchEnterKey }) : React24.createElement(Input, null),
fallback: rawJSONForm
}
) : rawJSONForm);
}, "ObjectControl");
// ../addons/docs/src/blocks/controls/Range.tsx
import React25, { useMemo as useMemo2 } from "react";
import { styled as styled19 } from "storybook/theming";
var RangeInput = styled19.input(
({ theme: theme3, min, max, value: value2, disabled }) => ({
// Resytled using http://danielstern.ca/range.css/#/
"&": {
width: "100%",
backgroundColor: "transparent",
appearance: "none"
},
"&::-webkit-slider-runnable-track": {
background: theme3.base === "light" ? `linear-gradient(to right,
${theme3.color.green} 0%, ${theme3.color.green} ${(value2 - min) / (max - min) * 100}%,
${curriedDarken$1(0.02, theme3.input.background)} ${(value2 - min) / (max - min) * 100}%,
${curriedDarken$1(0.02, theme3.input.background)} 100%)` : `linear-gradient(to right,
${theme3.color.green} 0%, ${theme3.color.green} ${(value2 - min) / (max - min) * 100}%,
${curriedLighten$1(0.02, theme3.input.background)} ${(value2 - min) / (max - min) * 100}%,
${curriedLighten$1(0.02, theme3.input.background)} 100%)`,
boxShadow: `${theme3.appBorderColor} 0 0 0 1px inset`,
borderRadius: 6,
width: "100%",
height: 6,
cursor: disabled ? "not-allowed" : "pointer"
},
"&::-webkit-slider-thumb": {
marginTop: "-6px",
width: 16,
height: 16,
border: `1px solid ${rgba(theme3.appBorderColor, 0.2)}`,
borderRadius: "50px",
boxShadow: `0 1px 3px 0px ${rgba(theme3.appBorderColor, 0.2)}`,
cursor: disabled ? "not-allowed" : "grab",
appearance: "none",
background: `${theme3.input.background}`,
transition: "all 150ms ease-out",
"&:hover": {
background: `${curriedDarken$1(0.05, theme3.input.background)}`,
transform: "scale3d(1.1, 1.1, 1.1) translateY(-1px)",
transition: "all 50ms ease-out"
},
"&:active": {
background: `${theme3.input.background}`,
transform: "scale3d(1, 1, 1) translateY(0px)",
cursor: disabled ? "not-allowed" : "grab"
}
},
"&:focus": {
outline: "none",
"&::-webkit-slider-runnable-track": {
borderColor: rgba(theme3.color.secondary, 0.4)
},
"&::-webkit-slider-thumb": {
borderColor: theme3.color.secondary,
boxShadow: `0 0px 5px 0px ${theme3.color.secondary}`
}
},
"&::-moz-range-track": {
background: theme3.base === "light" ? `linear-gradient(to right,
${theme3.color.green} 0%, ${theme3.color.green} ${(value2 - min) / (max - min) * 100}%,
${curriedDarken$1(0.02, theme3.input.background)} ${(value2 - min) / (max - min) * 100}%,
${curriedDarken$1(0.02, theme3.input.background)} 100%)` : `linear-gradient(to right,
${theme3.color.green} 0%, ${theme3.color.green} ${(value2 - min) / (max - min) * 100}%,
${curriedLighten$1(0.02, theme3.input.background)} ${(value2 - min) / (max - min) * 100}%,
${curriedLighten$1(0.02, theme3.input.background)} 100%)`,
boxShadow: `${theme3.appBorderColor} 0 0 0 1px inset`,
borderRadius: 6,
width: "100%",
height: 6,
cursor: disabled ? "not-allowed" : "pointer",
outline: "none"
},
"&::-moz-range-thumb": {
width: 16,
height: 16,
border: `1px solid ${rgba(theme3.appBorderColor, 0.2)}`,
borderRadius: "50px",
boxShadow: `0 1px 3px 0px ${rgba(theme3.appBorderColor, 0.2)}`,
cursor: disabled ? "not-allowed" : "grap",
background: `${theme3.input.background}`,
transition: "all 150ms ease-out",
"&:hover": {
background: `${curriedDarken$1(0.05, theme3.input.background)}`,
transform: "scale3d(1.1, 1.1, 1.1) translateY(-1px)",
transition: "all 50ms ease-out"
},
"&:active": {
background: `${theme3.input.background}`,
transform: "scale3d(1, 1, 1) translateY(0px)",
cursor: "grabbing"
}
},
"&::-ms-track": {
background: theme3.base === "light" ? `linear-gradient(to right,
${theme3.color.green} 0%, ${theme3.color.green} ${(value2 - min) / (max - min) * 100}%,
${curriedDarken$1(0.02, theme3.input.background)} ${(value2 - min) / (max - min) * 100}%,
${curriedDarken$1(0.02, theme3.input.background)} 100%)` : `linear-gradient(to right,
${theme3.color.green} 0%, ${theme3.color.green} ${(value2 - min) / (max - min) * 100}%,
${curriedLighten$1(0.02, theme3.input.background)} ${(value2 - min) / (max - min) * 100}%,
${curriedLighten$1(0.02, theme3.input.background)} 100%)`,
boxShadow: `${theme3.appBorderColor} 0 0 0 1px inset`,
color: "transparent",
width: "100%",
height: "6px",
cursor: "pointer"
},
"&::-ms-fill-lower": {
borderRadius: 6
},
"&::-ms-fill-upper": {
borderRadius: 6
},
"&::-ms-thumb": {
width: 16,
height: 16,
background: `${theme3.input.background}`,
border: `1px solid ${rgba(theme3.appBorderColor, 0.2)}`,
borderRadius: 50,
cursor: "grab",
marginTop: 0
},
"@supports (-ms-ime-align:auto)": { "input[type=range]": { margin: "0" } }
})
);
var RangeLabel = styled19.span({
paddingLeft: 5,
paddingRight: 5,
fontSize: 12,
whiteSpace: "nowrap",
fontFeatureSettings: "tnum",
fontVariantNumeric: "tabular-nums",
"[aria-readonly=true] &": {
opacity: 0.5
}
});
var RangeCurrentAndMaxLabel = styled19(RangeLabel)(({ numberOFDecimalsPlaces, max }) => ({
// Fixed width of "current / max" label to avoid slider width changes
// 3 = size of separator " / "
width: `${numberOFDecimalsPlaces + max.toString().length * 2 + 3}ch`,
textAlign: "right",
flexShrink: 0
}));
var RangeWrapper = styled19.div({
display: "flex",
alignItems: "center",
width: "100%"
});
function getNumberOfDecimalPlaces(number) {
const match = number.toString().match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
return !match ? 0 : Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0) - // Adjust for scientific notation.
(match[2] ? +match[2] : 0)
);
}
__name(getNumberOfDecimalPlaces, "getNumberOfDecimalPlaces");
var RangeControl = /* @__PURE__ */ __name(({
name,
value: value2,
onChange,
min = 0,
max = 100,
step = 1,
onBlur,
onFocus,
argType
}) => {
const handleChange = /* @__PURE__ */ __name((event) => {
onChange(parse2(event.target.value));
}, "handleChange");
const hasValue = value2 !== void 0;
const numberOFDecimalsPlaces = useMemo2(() => getNumberOfDecimalPlaces(step), [step]);
const readonly = !!argType?.table?.readonly;
return React25.createElement(RangeWrapper, { "aria-readonly": readonly }, React25.createElement(RangeLabel, null, min), React25.createElement(
RangeInput,
{
id: getControlId(name),
type: "range",
disabled: readonly,
onChange: handleChange,
...{ name, min, max, step, onFocus, onBlur },
value: value2 ?? min
}
), React25.createElement(RangeCurrentAndMaxLabel, { numberOFDecimalsPlaces, max }, hasValue ? value2.toFixed(numberOFDecimalsPlaces) : "--", " / ", max));
}, "RangeControl");
// ../addons/docs/src/blocks/controls/Text.tsx
import React26, { useCallback as useCallback5, useState as useState8 } from "react";
import { Button as Button4, Form as Form4 } from "storybook/internal/components";
import { styled as styled20 } from "storybook/theming";
var Wrapper8 = styled20.label({
display: "flex"
});
var MaxLength = styled20.div(({ isMaxed }) => ({
marginLeft: "0.75rem",
paddingTop: "0.35rem",
color: isMaxed ? "red" : void 0
}));
var TextControl = /* @__PURE__ */ __name(({
name,
value: value2,
onChange,
onFocus,
onBlur,
maxLength,
argType
}) => {
const handleChange = /* @__PURE__ */ __name((event) => {
onChange(event.target.value);
}, "handleChange");
const readonly = !!argType?.table?.readonly;
const [forceVisible, setForceVisible] = useState8(false);
const onForceVisible = useCallback5(() => {
onChange("");
setForceVisible(true);
}, [setForceVisible]);
if (value2 === void 0) {
return React26.createElement(
Button4,
{
variant: "outline",
size: "medium",
disabled: readonly,
id: getControlSetterButtonId(name),
onClick: onForceVisible
},
"Set string"
);
}
const isValid = typeof value2 === "string";
return React26.createElement(Wrapper8, null, React26.createElement(
Form4.Textarea,
{
id: getControlId(name),
maxLength,
onChange: handleChange,
disabled: readonly,
size: "flex",
placeholder: "Edit string...",
autoFocus: forceVisible,
valid: isValid ? void 0 : "error",
...{ name, value: isValid ? value2 : "", onFocus, onBlur }
}
), maxLength && React26.createElement(MaxLength, { isMaxed: value2?.length === maxLength }, value2?.length ?? 0, " / ", maxLength));
}, "TextControl");
// ../addons/docs/src/blocks/controls/Files.tsx
import React27, { useEffect as useEffect8, useRef as useRef5 } from "react";
import { Form as Form5 } from "storybook/internal/components";
import { styled as styled21 } from "storybook/theming";
var FileInput = styled21(Form5.Input)({
padding: 10
});
function revokeOldUrls(urls) {
urls.forEach((url) => {
if (url.startsWith("blob:")) {
URL.revokeObjectURL(url);
}
});
}
__name(revokeOldUrls, "revokeOldUrls");
var FilesControl = /* @__PURE__ */ __name(({
onChange,
name,
accept = "image/*",
value: value2,
argType
}) => {
const inputElement = useRef5(null);
const readonly = argType?.control?.readOnly;
function handleFileChange(e2) {
if (!e2.target.files) {
return;
}
const fileUrls = Array.from(e2.target.files).map((file) => URL.createObjectURL(file));
onChange(fileUrls);
revokeOldUrls(value2 || []);
}
__name(handleFileChange, "handleFileChange");
useEffect8(() => {
if (value2 == null && inputElement.current) {
inputElement.current.value = "";
}
}, [value2, name]);
return React27.createElement(
FileInput,
{
ref: inputElement,
id: getControlId(name),
type: "file",
name,
multiple: true,
disabled: readonly,
onChange: handleFileChange,
accept,
size: "flex"
}
);
}, "FilesControl");
// ../addons/docs/src/blocks/controls/index.tsx
var LazyColorControl = lazy(() => import("../../_browser-chunks/Color-7ZNS6F6B.js"));
var ColorControl = /* @__PURE__ */ __name((props) => React28.createElement(Suspense, { fallback: React28.createElement("div", null) }, React28.createElement(LazyColorControl, { ...props })), "ColorControl");
// ../addons/docs/src/blocks/components/ArgsTable/ArgControl.tsx
var Controls2 = {
array: ObjectControl,
object: ObjectControl,
boolean: BooleanControl,
color: ColorControl,
date: DateControl,
number: NumberControl,
check: OptionsControl,
"inline-check": OptionsControl,
radio: OptionsControl,
"inline-radio": OptionsControl,
select: OptionsControl,
"multi-select": OptionsControl,
range: RangeControl,
text: TextControl,
file: FilesControl
};
var NoControl = /* @__PURE__ */ __name(() => React29.createElement(React29.Fragment, null, "-"), "NoControl");
var ArgControl = /* @__PURE__ */ __name(({ row, arg, updateArgs, isHovered }) => {
const { key, control } = row;
const [isFocused, setFocused] = useState9(false);
const [boxedValue, setBoxedValue] = useState9({ value: arg });
useEffect9(() => {
if (!isFocused) {
setBoxedValue({ value: arg });
}
}, [isFocused, arg]);
const onChange = useCallback6(
(argVal) => {
setBoxedValue({ value: argVal });
updateArgs({ [key]: argVal });
return argVal;
},
[updateArgs, key]
);
const onBlur = useCallback6(() => setFocused(false), []);
const onFocus = useCallback6(() => setFocused(true), []);
if (!control || control.disable) {
const canBeSetup = control?.disable !== true && row?.type?.name !== "function";
return isHovered && canBeSetup ? React29.createElement(
Link,
{
href: "https://storybook.js.org/docs/essentials/controls?ref=ui",
target: "_blank",
withArrow: true
},
"Setup controls"
) : React29.createElement(NoControl, null);
}
const props = { name: key, argType: row, value: boxedValue.value, onChange, onBlur, onFocus };
const Control = Controls2[control.type] || NoControl;
return React29.createElement(Control, { ...props, ...control, controlType: control.type });
}, "ArgControl");
// ../addons/docs/src/blocks/components/ArgsTable/ArgJsDoc.tsx
import React30 from "react";
import { codeCommon } from "storybook/internal/components";
import { styled as styled22 } from "storybook/theming";
var Table = styled22.table(({ theme: theme3 }) => ({
"&&": {
// Escape default table styles
borderCollapse: "collapse",
borderSpacing: 0,
border: "none",
tr: {
border: "none !important",
background: "none"
},
"td, th": {
padding: 0,
border: "none",
width: "auto!important"
},
// End escape
marginTop: 0,
marginBottom: 0,
"th:first-of-type, td:first-of-type": {
paddingLeft: 0
},
"th:last-of-type, td:last-of-type": {
paddingRight: 0
},
td: {
paddingTop: 0,
paddingBottom: 4,
"&:not(:first-of-type)": {
paddingLeft: 10,
paddingRight: 0
}
},
tbody: {
boxShadow: "none",
border: "none"
},
code: codeCommon({ theme: theme3 }),
div: {
span: {
fontWeight: "bold"
}
},
"& code": {
margin: 0,
display: "inline-block",
fontSize: theme3.typography.size.s1
}
}
}));
var ArgJsDoc = /* @__PURE__ */ __name(({ tags }) => {
const params = (tags.params || []).filter((x2) => x2.description);
const hasDisplayableParams = params.length !== 0;
const hasDisplayableDeprecated = tags.deprecated != null;
const hasDisplayableReturns = tags.returns != null && tags.returns.description != null;
if (!hasDisplayableParams && !hasDisplayableReturns && !hasDisplayableDeprecated) {
return null;
}
return React30.createElement(React30.Fragment, null, React30.createElement(Table, null, React30.createElement("tbody", null, hasDisplayableDeprecated && React30.createElement("tr", { key: "deprecated" }, React30.createElement("td", { colSpan: 2 }, React30.createElement("strong", null, "Deprecated"), ": ", tags.deprecated?.toString())), hasDisplayableParams && params.map((x2) => {
return React30.createElement("tr", { key: x2.name }, React30.createElement("td", null, React30.createElement("code", null, x2.name)), React30.createElement("td", null, x2.description));
}), hasDisplayableReturns && React30.createElement("tr", { key: "returns" }, React30.createElement("td", null, React30.createElement("code", null, "Returns")), React30.createElement("td", null, tags.returns?.description)))));
}, "ArgJsDoc");
// ../addons/docs/src/blocks/components/ArgsTable/ArgValue.tsx
import React31, { useState as useState10 } from "react";
import { SyntaxHighlighter as SyntaxHighlighter2, WithTooltipPure, codeCommon as codeCommon2 } from "storybook/internal/components";
import { ChevronSmallDownIcon as ChevronSmallDownIcon2, ChevronSmallUpIcon } from "@storybook/icons";
var import_memoizerific = __toESM(require_memoizerific(), 1);
import { styled as styled23 } from "storybook/theming";
var ITEMS_BEFORE_EXPANSION = 8;
var Summary = styled23.div(({ isExpanded }) => ({
display: "flex",
flexDirection: isExpanded ? "column" : "row",
flexWrap: "wrap",
alignItems: "flex-start",
marginBottom: "-4px",
minWidth: 100
}));
var Text3 = styled23.span(codeCommon2, ({ theme: theme3, simple = false }) => ({
flex: "0 0 auto",
fontFamily: theme3.typography.fonts.mono,
fontSize: theme3.typography.size.s1,
wordBreak: "break-word",
whiteSpace: "normal",
maxWidth: "100%",
margin: 0,
marginRight: "4px",
marginBottom: "4px",
paddingTop: "2px",
paddingBottom: "2px",
lineHeight: "13px",
...simple && {
background: "transparent",
border: "0 none",
paddingLeft: 0
}
}));
var ExpandButton = styled23.button(({ theme: theme3 }) => ({
fontFamily: theme3.typography.fonts.mono,
color: theme3.color.secondary,
marginBottom: "4px",
background: "none",
border: "none"
}));
var Expandable = styled23.div(codeCommon2, ({ theme: theme3 }) => ({
fontFamily: theme3.typography.fonts.mono,
color: theme3.color.secondary,
fontSize: theme3.typography.size.s1,
// overrides codeCommon
margin: 0,
whiteSpace: "nowrap",
display: "flex",
alignItems: "center"
}));
var Detail = styled23.div(({ theme: theme3, width }) => ({
width,
minWidth: 200,
maxWidth: 800,
padding: 15,
// Don't remove the mono fontFamily here even if it seems useless, this is used by the browser to calculate the length of a "ch" unit.
fontFamily: theme3.typography.fonts.mono,
fontSize: theme3.typography.size.s1,
// Most custom stylesheet will reset the box-sizing to "border-box" and will break the tooltip.
boxSizing: "content-box",
"& code": {
padding: "0 !important"
}
}));
var ChevronUpIcon = styled23(ChevronSmallUpIcon)({
marginLeft: 4
});
var ChevronDownIcon = styled23(ChevronSmallDownIcon2)({
marginLeft: 4
});
var EmptyArg = /* @__PURE__ */ __name(() => {
return React31.createElement("span", null, "-");
}, "EmptyArg");
var ArgText = /* @__PURE__ */ __name(({ text, simple }) => {
return React31.createElement(Text3, { simple }, text);
}, "ArgText");
var calculateDetailWidth = (0, import_memoizerific.default)(1e3)((detail) => {
const lines = detail.split(/\r?\n/);
return `${Math.max(...lines.map((x2) => x2.length))}ch`;
});
var getSummaryItems = /* @__PURE__ */ __name((summary) => {
if (!summary) {
return [summary];
}
const splittedItems = summary.split("|");
const summaryItems = splittedItems.map((value2) => value2.trim());
return uniq(summaryItems);
}, "getSummaryItems");
var renderSummaryItems = /* @__PURE__ */ __name((summaryItems, isExpanded = true) => {
let items = summaryItems;
if (!isExpanded) {
items = summaryItems.slice(0, ITEMS_BEFORE_EXPANSION);
}
return items.map((item) => React31.createElement(ArgText, { key: item, text: item === "" ? '""' : item }));
}, "renderSummaryItems");
var ArgSummary = /* @__PURE__ */ __name(({ value: value2, initialExpandedArgs }) => {
const { summary, detail } = value2;
const [isOpen, setIsOpen] = useState10(false);
const [isExpanded, setIsExpanded] = useState10(initialExpandedArgs || false);
if (summary === void 0 || summary === null) {
return null;
}
const summaryAsString = typeof summary.toString === "function" ? summary.toString() : summary;
if (detail == null) {
const cannotBeSafelySplitted = /[(){}[\]<>]/.test(summaryAsString);
if (cannotBeSafelySplitted) {
return React31.createElement(ArgText, { text: summaryAsString });
}
const summaryItems = getSummaryItems(summaryAsString);
const itemsCount = summaryItems.length;
const hasManyItems = itemsCount > ITEMS_BEFORE_EXPANSION;
return hasManyItems ? React31.createElement(Summary, { isExpanded }, renderSummaryItems(summaryItems, isExpanded), React31.createElement(ExpandButton, { onClick: () => setIsExpanded(!isExpanded) }, isExpanded ? "Show less..." : `Show ${itemsCount - ITEMS_BEFORE_EXPANSION} more...`)) : React31.createElement(Summary, null, renderSummaryItems(summaryItems));
}
return React31.createElement(
WithTooltipPure,
{
closeOnOutsideClick: true,
placement: "bottom",
visible: isOpen,
onVisibleChange: (isVisible) => {
setIsOpen(isVisible);
},
tooltip: React31.createElement(Detail, { width: calculateDetailWidth(detail) }, React31.createElement(SyntaxHighlighter2, { language: "jsx", format: false }, detail))
},
React31.createElement(Expandable, { className: "sbdocs-expandable" }, React31.createElement("span", null, summaryAsString), isOpen ? React31.createElement(ChevronUpIcon, null) : React31.createElement(ChevronDownIcon, null))
);
}, "ArgSummary");
var ArgValue = /* @__PURE__ */ __name(({ value: value2, initialExpandedArgs }) => {
return value2 == null ? React31.createElement(EmptyArg, null) : React31.createElement(ArgSummary, { value: value2, initialExpandedArgs });
}, "ArgValue");
// ../addons/docs/src/blocks/components/ArgsTable/ArgRow.tsx
var Name = styled24.span({ fontWeight: "bold" });
var Required = styled24.span(({ theme: theme3 }) => ({
color: theme3.color.negative,
fontFamily: theme3.typography.fonts.mono,
cursor: "help"
}));
var Description = styled24.div(({ theme: theme3 }) => ({
"&&": {
p: {
margin: "0 0 10px 0"
},
a: {
color: theme3.color.secondary
}
},
code: {
...codeCommon3({ theme: theme3 }),
fontSize: 12,
fontFamily: theme3.typography.fonts.mono
},
"& code": {
margin: 0,
display: "inline-block"
},
"& pre > code": {
whiteSpace: "pre-wrap"
}
}));
var Type = styled24.div(({ theme: theme3, hasDescription }) => ({
color: theme3.base === "light" ? curriedTransparentize$1(0.1, theme3.color.defaultText) : curriedTransparentize$1(0.2, theme3.color.defaultText),
marginTop: hasDescription ? 4 : 0
}));
var TypeWithJsDoc = styled24.div(({ theme: theme3, hasDescription }) => ({
color: theme3.base === "light" ? curriedTransparentize$1(0.1, theme3.color.defaultText) : curriedTransparentize$1(0.2, theme3.color.defaultText),
marginTop: hasDescription ? 12 : 0,
marginBottom: 12
}));
var StyledTd = styled24.td(({ expandable }) => ({
paddingLeft: expandable ? "40px !important" : "20px !important"
}));
var toSummary = /* @__PURE__ */ __name((value2) => {
if (!value2) {
return value2;
}
const val = typeof value2 === "string" ? value2 : value2.name;
return { summary: val };
}, "toSummary");
var ArgRow = /* @__PURE__ */ __name((props) => {
const [isHovered, setIsHovered] = useState11(false);
const { row, updateArgs, compact, expandable, initialExpandedArgs } = props;
const { name, description } = row;
const table = row.table || {};
const type = table.type || toSummary(row.type);
const defaultValue = table.defaultValue || row.defaultValue;
const required = row.type?.required;
const hasDescription = description != null && description !== "";
return React32.createElement("tr", { onMouseEnter: () => setIsHovered(true), onMouseLeave: () => setIsHovered(false) }, React32.createElement(StyledTd, { expandable: expandable ?? false }, React32.createElement(Name, null, name), required ? React32.createElement(Required, { title: "Required" }, "*") : null), compact ? null : React32.createElement("td", null, hasDescription && React32.createElement(Description, null, React32.createElement(index_modern_default, null, description)), table.jsDocTags != null ? React32.createElement(React32.Fragment, null, React32.createElement(TypeWithJsDoc, { hasDescription }, React32.createElement(ArgValue, { value: type, initialExpandedArgs })), React32.createElement(ArgJsDoc, { tags: table.jsDocTags })) : React32.createElement(Type, { hasDescription }, React32.createElement(ArgValue, { value: type, initialExpandedArgs }))), compact ? null : React32.createElement("td", null, React32.createElement(ArgValue, { value: defaultValue, initialExpandedArgs })), updateArgs ? React32.createElement("td", null, React32.createElement(ArgControl, { ...props, isHovered })) : null);
}, "ArgRow");
// ../addons/docs/src/blocks/components/ArgsTable/Empty.tsx
import React33, { useEffect as useEffect10, useState as useState12 } from "react";
import { EmptyTabContent, Link as Link2 } from "storybook/internal/components";
import { DocumentIcon } from "@storybook/icons";
import { styled as styled25 } from "storybook/theming";
var Wrapper9 = styled25.div(({ inAddonPanel, theme: theme3 }) => ({
height: inAddonPanel ? "100%" : "auto",
display: "flex",
border: inAddonPanel ? "none" : `1px solid ${theme3.appBorderColor}`,
borderRadius: inAddonPanel ? 0 : theme3.appBorderRadius,
padding: inAddonPanel ? 0 : 40,
alignItems: "center",
justifyContent: "center",
flexDirection: "column",
gap: 15,
background: theme3.background.content
}));
var Links = styled25.div(({ theme: theme3 }) => ({
display: "flex",
fontSize: theme3.typography.size.s2 - 1,
gap: 25
}));
var Empty = /* @__PURE__ */ __name(({ inAddonPanel }) => {
const [isLoading, setIsLoading] = useState12(true);
useEffect10(() => {
const load = setTimeout(() => {
setIsLoading(false);
}, 100);
return () => clearTimeout(load);
}, []);
if (isLoading) {
return null;
}
return React33.createElement(Wrapper9, { inAddonPanel }, React33.createElement(
EmptyTabContent,
{
title: inAddonPanel ? "Interactive story playground" : "Args table with interactive controls couldn't be auto-generated",
description: React33.createElement(React33.Fragment, null, "Controls give you an easy to use interface to test your components. Set your story args and you'll see controls appearing here automatically."),
footer: React33.createElement(Links, null, inAddonPanel && React33.createElement(React33.Fragment, null, React33.createElement(
Link2,
{
href: "https://storybook.js.org/docs/essentials/controls?ref=ui",
target: "_blank",
withArrow: true
},
React33.createElement(DocumentIcon, null),
" Read docs"
)), !inAddonPanel && React33.createElement(
Link2,
{
href: "https://storybook.js.org/docs/essentials/controls?ref=ui",
target: "_blank",
withArrow: true
},
React33.createElement(DocumentIcon, null),
" Learn how to set that up"
))
}
));
}, "Empty");
// ../addons/docs/src/blocks/components/ArgsTable/SectionRow.tsx
import React34, { useState as useState13 } from "react";
import { ChevronDownIcon as ChevronDownIcon2, ChevronRightIcon } from "@storybook/icons";
import { styled as styled26 } from "storybook/theming";
var ExpanderIconDown = styled26(ChevronDownIcon2)(({ theme: theme3 }) => ({
marginRight: 8,
marginLeft: -10,
marginTop: -2,
// optical alignment
height: 12,
width: 12,
color: theme3.base === "light" ? curriedTransparentize$1(0.25, theme3.color.defaultText) : curriedTransparentize$1(0.3, theme3.color.defaultText),
border: "none",
display: "inline-block"
}));
var ExpanderIconRight = styled26(ChevronRightIcon)(({ theme: theme3 }) => ({
marginRight: 8,
marginLeft: -10,
marginTop: -2,
// optical alignment
height: 12,
width: 12,
color: theme3.base === "light" ? curriedTransparentize$1(0.25, theme3.color.defaultText) : curriedTransparentize$1(0.3, theme3.color.defaultText),
border: "none",
display: "inline-block"
}));
var FlexWrapper = styled26.span(({ theme: theme3 }) => ({
display: "flex",
lineHeight: "20px",
alignItems: "center"
}));
var Section = styled26.td(({ theme: theme3 }) => ({
position: "relative",
letterSpacing: "0.35em",
textTransform: "uppercase",
fontWeight: theme3.typography.weight.bold,
fontSize: theme3.typography.size.s1 - 1,
color: theme3.base === "light" ? curriedTransparentize$1(0.4, theme3.color.defaultText) : curriedTransparentize$1(0.6, theme3.color.defaultText),
background: `${theme3.background.app} !important`,
"& ~ td": {
background: `${theme3.background.app} !important`
}
}));
var Subsection = styled26.td(({ theme: theme3 }) => ({
position: "relative",
fontWeight: theme3.typography.weight.bold,
fontSize: theme3.typography.size.s2 - 1,
background: theme3.background.app
}));
var StyledTd2 = styled26.td({
position: "relative"
});
var StyledTr = styled26.tr(({ theme: theme3 }) => ({
"&:hover > td": {
backgroundColor: `${curriedLighten$1(5e-3, theme3.background.app)} !important`,
boxShadow: `${theme3.color.mediumlight} 0 - 1px 0 0 inset`,
cursor: "row-resize"
}
}));
var ClickIntercept = styled26.button({
// reset button style
background: "none",
border: "none",
padding: "0",
font: "inherit",
// add custom style
position: "absolute",
top: 0,
bottom: 0,
left: 0,
right: 0,
height: "100%",
width: "100%",
color: "transparent",
cursor: "row-resize !important"
});
var SectionRow = /* @__PURE__ */ __name(({
level = "section",
label,
children,
initialExpanded = true,
colSpan = 3
}) => {
const [expanded, setExpanded] = useState13(initialExpanded);
const Level = level === "subsection" ? Subsection : Section;
const itemCount = children?.length || 0;
const caption = level === "subsection" ? `${itemCount} item${itemCount !== 1 ? "s" : ""}` : "";
const helperText = `${expanded ? "Hide" : "Show"} ${level === "subsection" ? itemCount : label} item${itemCount !== 1 ? "s" : ""}`;
return React34.createElement(React34.Fragment, null, React34.createElement(StyledTr, { title: helperText }, React34.createElement(Level, { colSpan: 1 }, React34.createElement(ClickIntercept, { onClick: (e2) => setExpanded(!expanded), tabIndex: 0 }, helperText), React34.createElement(FlexWrapper, null, expanded ? React34.createElement(ExpanderIconDown, null) : React34.createElement(ExpanderIconRight, null), label)), React34.createElement(StyledTd2, { colSpan: colSpan - 1 }, React34.createElement(
ClickIntercept,
{
onClick: (e2) => setExpanded(!expanded),
tabIndex: -1,
style: { outline: "none" }
},
helperText
), expanded ? null : caption)), expanded ? children : null);
}, "SectionRow");
// ../addons/docs/src/blocks/components/ArgsTable/Skeleton.tsx
import React35 from "react";
import { styled as styled27 } from "storybook/theming";
var TableWrapper = styled27.div(({ theme: theme3 }) => ({
width: "100%",
borderSpacing: 0,
color: theme3.color.defaultText
}));
var Row = styled27.div(({ theme: theme3 }) => ({
display: "flex",
borderBottom: `1px solid ${theme3.appBorderColor}`,
"&:last-child": {
borderBottom: 0
}
}));
var Column = styled27.div(
({ position, theme: theme3 }) => {
const baseStyles = {
display: "flex",
flexDirection: "column",
gap: 5,
padding: "10px 15px",
alignItems: "flex-start"
};
switch (position) {
case "first":
return {
...baseStyles,
width: "25%",
paddingLeft: 20
};
case "second":
return {
...baseStyles,
width: "35%"
};
case "third":
return {
...baseStyles,
width: "15%"
};
case "last":
return {
...baseStyles,
width: "25%",
paddingRight: 20
};
}
}
);
var SkeletonText = styled27.div(
({ theme: theme3, width, height }) => ({
animation: `${theme3.animation.glow} 1.5s ease-in-out infinite`,
background: theme3.appBorderColor,
width: width || "100%",
height: height || 16,
borderRadius: 3
})
);
var Skeleton = /* @__PURE__ */ __name(() => React35.createElement(TableWrapper, null, React35.createElement(Row, null, React35.createElement(Column, { position: "first" }, React35.createElement(SkeletonText, { width: "60%" })), React35.createElement(Column, { position: "second" }, React35.createElement(SkeletonText, { width: "30%" })), React35.createElement(Column, { position: "third" }, React35.createElement(SkeletonText, { width: "60%" })), React35.createElement(Column, { position: "last" }, React35.createElement(SkeletonText, { width: "60%" }))), React35.createElement(Row, null, React35.createElement(Column, { position: "first" }, React35.createElement(SkeletonText, { width: "60%" })), React35.createElement(Column, { position: "second" }, React35.createElement(SkeletonText, { width: "80%" }), React35.createElement(SkeletonText, { width: "30%" })), React35.createElement(Column, { position: "third" }, React35.createElement(SkeletonText, { width: "60%" })), React35.createElement(Column, { position: "last" }, React35.createElement(SkeletonText, { width: "60%" }))), React35.createElement(Row, null, React35.createElement(Column, { position: "first" }, React35.createElement(SkeletonText, { width: "60%" })), React35.createElement(Column, { position: "second" }, React35.createElement(SkeletonText, { width: "80%" }), React35.createElement(SkeletonText, { width: "30%" })), React35.createElement(Column, { position: "third" }, React35.createElement(SkeletonText, { width: "60%" })), React35.createElement(Column, { position: "last" }, React35.createElement(SkeletonText, { width: "60%" }))), React35.createElement(Row, null, React35.createElement(Column, { position: "first" }, React35.createElement(SkeletonText, { width: "60%" })), React35.createElement(Column, { position: "second" }, React35.createElement(SkeletonText, { width: "80%" }), React35.createElement(SkeletonText, { width: "30%" })), React35.createElement(Column, { position: "third" }, React35.createElement(SkeletonText, { width: "60%" })), React35.createElement(Column, { position: "last" }, React35.createElement(SkeletonText, { width: "60%" })))), "Skeleton");
// ../addons/docs/src/blocks/components/ArgsTable/ArgsTable.tsx
var TableWrapper2 = styled28.table(({ theme: theme3, compact, inAddonPanel }) => ({
"&&": {
// Resets for cascading/system styles
borderSpacing: 0,
color: theme3.color.defaultText,
"td, th": {
padding: 0,
border: "none",
verticalAlign: "top",
textOverflow: "ellipsis"
},
// End Resets
fontSize: theme3.typography.size.s2 - 1,
lineHeight: "20px",
textAlign: "left",
width: "100%",
// Margin collapse
marginTop: inAddonPanel ? 0 : 25,
marginBottom: inAddonPanel ? 0 : 40,
"thead th:first-of-type, td:first-of-type": {
// intentionally specify thead here
width: "25%"
},
"th:first-of-type, td:first-of-type": {
paddingLeft: 20
},
"th:nth-of-type(2), td:nth-of-type(2)": {
...compact ? null : {
// Description column
width: "35%"
}
},
"td:nth-of-type(3)": {
...compact ? null : {
// Defaults column
width: "15%"
}
},
"th:last-of-type, td:last-of-type": {
paddingRight: 20,
...compact ? null : {
// Controls column
width: "25%"
}
},
th: {
color: theme3.base === "light" ? curriedTransparentize$1(0.25, theme3.color.defaultText) : curriedTransparentize$1(0.45, theme3.color.defaultText),
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 15,
paddingRight: 15
},
td: {
paddingTop: "10px",
paddingBottom: "10px",
"&:not(:first-of-type)": {
paddingLeft: 15,
paddingRight: 15
},
"&:last-of-type": {
paddingRight: 20
}
},
// Makes border alignment consistent w/other DocBlocks
marginLeft: inAddonPanel ? 0 : 1,
marginRight: inAddonPanel ? 0 : 1,
tbody: {
// Safari doesn't love shadows on tbody so we need to use a shadow filter. In order to do this,
// the table cells all need to be solid so they have a background color applied.
// I wasn't sure what kinds of content go in these tables so I was extra specific with selectors
// to avoid unexpected surprises.
...inAddonPanel ? null : {
filter: theme3.base === "light" ? `drop-shadow(0px 1px 3px rgba(0, 0, 0, 0.10))` : `drop-shadow(0px 1px 3px rgba(0, 0, 0, 0.20))`
},
"> tr > *": {
// For filter to work properly, the table cells all need to be opaque.
background: theme3.background.content,
borderTop: `1px solid ${theme3.appBorderColor}`
},
...inAddonPanel ? null : {
// This works and I don't know why. :)
"> tr:first-of-type > *": {
borderBlockStart: `1px solid ${theme3.appBorderColor}`
},
"> tr:last-of-type > *": {
borderBlockEnd: `1px solid ${theme3.appBorderColor}`
},
"> tr > *:first-of-type": {
borderInlineStart: `1px solid ${theme3.appBorderColor}`
},
"> tr > *:last-of-type": {
borderInlineEnd: `1px solid ${theme3.appBorderColor}`
},
// Thank you, Safari, for making me write code like this.
"> tr:first-of-type > td:first-of-type": {
borderTopLeftRadius: theme3.appBorderRadius
},
"> tr:first-of-type > td:last-of-type": {
borderTopRightRadius: theme3.appBorderRadius
},
"> tr:last-of-type > td:first-of-type": {
borderBottomLeftRadius: theme3.appBorderRadius
},
"> tr:last-of-type > td:last-of-type": {
borderBottomRightRadius: theme3.appBorderRadius
}
}
}
// End awesome table styling
}
}));
var TablePositionWrapper = styled28.div({
position: "relative"
});
var ButtonPositionWrapper = styled28.div({
position: "absolute",
right: 8,
top: 6
});
var sortFns = {
alpha: /* @__PURE__ */ __name((a2, b2) => (a2.name ?? "").localeCompare(b2.name ?? ""), "alpha"),
requiredFirst: /* @__PURE__ */ __name((a2, b2) => Number(!!b2.type?.required) - Number(!!a2.type?.required) || (a2.name ?? "").localeCompare(b2.name ?? ""), "requiredFirst"),
none: null
};
var groupRows = /* @__PURE__ */ __name((rows, sort) => {
const sections = { ungrouped: [], ungroupedSubsections: {}, sections: {} };
if (!rows) {
return sections;
}
Object.entries(rows).forEach(([key, row]) => {
const { category, subcategory } = row?.table || {};
if (category) {
const section = sections.sections[category] || { ungrouped: [], subsections: {} };
if (!subcategory) {
section.ungrouped.push({ key, ...row });
} else {
const subsection = section.subsections[subcategory] || [];
subsection.push({ key, ...row });
section.subsections[subcategory] = subsection;
}
sections.sections[category] = section;
} else if (subcategory) {
const subsection = sections.ungroupedSubsections[subcategory] || [];
subsection.push({ key, ...row });
sections.ungroupedSubsections[subcategory] = subsection;
} else {
sections.ungrouped.push({ key, ...row });
}
});
const sortFn = sortFns[sort];
const sortSubsection = /* @__PURE__ */ __name((record) => {
if (!sortFn) {
return record;
}
return Object.keys(record).reduce(
(acc, cur) => ({
...acc,
[cur]: record[cur].sort(sortFn)
}),
{}
);
}, "sortSubsection");
const sorted = {
ungrouped: sortFn ? sections.ungrouped.sort(sortFn) : sections.ungrouped,
ungroupedSubsections: sortSubsection(sections.ungroupedSubsections),
sections: Object.keys(sections.sections).reduce(
(acc, cur) => ({
...acc,
[cur]: {
ungrouped: sortFn ? sections.sections[cur].ungrouped.sort(sortFn) : sections.sections[cur].ungrouped,
subsections: sortSubsection(sections.sections[cur].subsections)
}
}),
{}
)
};
return sorted;
}, "groupRows");
var safeIncludeConditionalArg = /* @__PURE__ */ __name((row, args, globals) => {
try {
return includeConditionalArg(row, args, globals);
} catch (err) {
once.warn(err.message);
return false;
}
}, "safeIncludeConditionalArg");
var ArgsTable = /* @__PURE__ */ __name((props) => {
const {
updateArgs,
resetArgs,
compact,
inAddonPanel,
initialExpandedArgs,
sort = "none",
isLoading
} = props;
if ("error" in props) {
const { error } = props;
return React36.createElement(EmptyBlock, null, error, "\xA0", React36.createElement(Link3, { href: "http://storybook.js.org/docs/?ref=ui", target: "_blank", withArrow: true }, React36.createElement(DocumentIcon2, null), " Read the docs"));
}
if (isLoading) {
return React36.createElement(Skeleton, null);
}
const { rows, args, globals } = "rows" in props ? props : { rows: void 0, args: void 0, globals: void 0 };
const groups = groupRows(
pickBy(
rows || {},
(row) => !row?.table?.disable && safeIncludeConditionalArg(row, args || {}, globals || {})
),
sort
);
const hasNoUngrouped = groups.ungrouped.length === 0;
const hasNoSections = Object.entries(groups.sections).length === 0;
const hasNoUngroupedSubsections = Object.entries(groups.ungroupedSubsections).length === 0;
if (hasNoUngrouped && hasNoSections && hasNoUngroupedSubsections) {
return React36.createElement(Empty, { inAddonPanel });
}
let colSpan = 1;
if (updateArgs) {
colSpan += 1;
}
if (!compact) {
colSpan += 2;
}
const expandable = Object.keys(groups.sections).length > 0;
const common = { updateArgs, compact, inAddonPanel, initialExpandedArgs };
return React36.createElement(ResetWrapper3, null, React36.createElement(TablePositionWrapper, null, updateArgs && !isLoading && resetArgs && React36.createElement(ButtonPositionWrapper, null, React36.createElement(
IconButton3,
{
onClick: () => resetArgs(),
"aria-label": "Reset controls",
title: "Reset controls"
},
React36.createElement(UndoIcon, null)
)), React36.createElement(TableWrapper2, { ...{ compact, inAddonPanel }, className: "docblock-argstable sb-unstyled" }, React36.createElement("thead", { className: "docblock-argstable-head" }, React36.createElement("tr", null, React36.createElement("th", null, React36.createElement("span", null, "Name")), compact ? null : React36.createElement("th", null, React36.createElement("span", null, "Description")), compact ? null : React36.createElement("th", null, React36.createElement("span", null, "Default")), updateArgs ? React36.createElement("th", null, React36.createElement("span", null, "Control")) : null)), React36.createElement("tbody", { className: "docblock-argstable-body" }, groups.ungrouped.map((row) => React36.createElement(ArgRow, { key: row.key, row, arg: args && args[row.key], ...common })), Object.entries(groups.ungroupedSubsections).map(([subcategory, subsection]) => React36.createElement(
SectionRow,
{
key: subcategory,
label: subcategory,
level: "subsection",
colSpan
},
subsection.map((row) => React36.createElement(
ArgRow,
{
key: row.key,
row,
arg: args && args[row.key],
expandable,
...common
}
))
)), Object.entries(groups.sections).map(([category, section]) => React36.createElement(SectionRow, { key: category, label: category, level: "section", colSpan }, section.ungrouped.map((row) => React36.createElement(ArgRow, { key: row.key, row, arg: args && args[row.key], ...common })), Object.entries(section.subsections).map(([subcategory, subsection]) => React36.createElement(
SectionRow,
{
key: subcategory,
label: subcategory,
level: "subsection",
colSpan
},
subsection.map((row) => React36.createElement(
ArgRow,
{
key: row.key,
row,
arg: args && args[row.key],
expandable,
...common
}
))
))))))));
}, "ArgsTable");
// src/controls/constants.ts
var ADDON_ID6 = "addon-controls";
var PARAM_KEY5 = "controls";
// src/controls/components/SaveStory.tsx
import React37 from "react";
import {
Bar as BaseBar,
Button as Button5,
Form as Form6,
IconButton as IconButton4,
Modal,
TooltipNote,
WithTooltip
} from "storybook/internal/components";
import { AddIcon as AddIcon2, CheckIcon, UndoIcon as UndoIcon2 } from "@storybook/icons";
import { keyframes, styled as styled29 } from "storybook/theming";
var slideIn = keyframes({
from: { transform: "translateY(40px)" },
to: { transform: "translateY(0)" }
});
var highlight = keyframes({
from: { background: "var(--highlight-bg-color)" },
to: {}
});
var Container2 = styled29.div({
containerType: "size",
position: "sticky",
bottom: 0,
height: 39,
overflow: "hidden",
zIndex: 1
});
var Bar2 = styled29(BaseBar)(({ theme: theme3 }) => ({
"--highlight-bg-color": theme3.base === "dark" ? "#153B5B" : "#E0F0FF",
display: "flex",
flexDirection: "row-reverse",
// hide Info rather than Actions on overflow
alignItems: "center",
justifyContent: "space-between",
flexWrap: "wrap",
gap: 6,
padding: "6px 10px",
animation: `${slideIn} 300ms, ${highlight} 2s`,
background: theme3.background.bar,
borderTop: `1px solid ${theme3.appBorderColor}`,
fontSize: theme3.typography.size.s2,
"@container (max-width: 799px)": {
flexDirection: "row",
justifyContent: "flex-end"
}
}));
var Info = styled29.div({
display: "flex",
flex: "99 0 auto",
alignItems: "center",
marginLeft: 10,
gap: 6
});
var Actions = styled29.div(({ theme: theme3 }) => ({
display: "flex",
flex: "1 0 0",
alignItems: "center",
gap: 2,
color: theme3.color.mediumdark,
fontSize: theme3.typography.size.s2
}));
var Label5 = styled29.div({
"@container (max-width: 799px)": {
lineHeight: 0,
textIndent: "-9999px",
"&::after": {
content: "attr(data-short-label)",
display: "block",
lineHeight: "initial",
textIndent: "0"
}
}
});
var ModalInput = styled29(Form6.Input)(({ theme: theme3 }) => ({
"::placeholder": {
color: theme3.color.mediumdark
},
"&:invalid:not(:placeholder-shown)": {
boxShadow: `${theme3.color.negative} 0 0 0 1px inset`
}
}));
var SaveStory = /* @__PURE__ */ __name(({
saveStory,
createStory,
resetArgs,
portalSelector
}) => {
const inputRef = React37.useRef(null);
const [saving, setSaving] = React37.useState(false);
const [creating, setCreating] = React37.useState(false);
const [storyName, setStoryName] = React37.useState("");
const [errorMessage, setErrorMessage] = React37.useState(null);
const onSaveStory = /* @__PURE__ */ __name(async () => {
if (saving) {
return;
}
setSaving(true);
await saveStory().catch(() => {
});
setSaving(false);
}, "onSaveStory");
const onShowForm = /* @__PURE__ */ __name(() => {
setCreating(true);
setStoryName("");
setTimeout(() => inputRef.current?.focus(), 0);
}, "onShowForm");
const onChange = /* @__PURE__ */ __name((e2) => {
const value2 = e2.target.value.replace(/^[^a-z]/i, "").replace(/[^a-z0-9-_ ]/gi, "").replaceAll(/([-_ ]+[a-z0-9])/gi, (match) => match.toUpperCase().replace(/[-_ ]/g, ""));
setStoryName(value2.charAt(0).toUpperCase() + value2.slice(1));
}, "onChange");
const onSubmitForm = /* @__PURE__ */ __name(async (event) => {
event.preventDefault();
if (saving) {
return;
}
try {
setErrorMessage(null);
setSaving(true);
await createStory(storyName.replace(/^[^a-z]/i, "").replaceAll(/[^a-z0-9]/gi, ""));
setCreating(false);
setSaving(false);
} catch (e2) {
setErrorMessage(e2.message);
setSaving(false);
}
}, "onSubmitForm");
return React37.createElement(Container2, { id: "save-from-controls" }, React37.createElement(Bar2, null, React37.createElement(Actions, null, React37.createElement(
WithTooltip,
{
as: "div",
hasChrome: false,
trigger: "hover",
tooltip: React37.createElement(TooltipNote, { note: "Save changes to story" })
},
React37.createElement(IconButton4, { "aria-label": "Save changes to story", disabled: saving, onClick: onSaveStory }, React37.createElement(CheckIcon, null), React37.createElement(Label5, { "data-short-label": "Save" }, "Update story"))
), React37.createElement(
WithTooltip,
{
as: "div",
hasChrome: false,
trigger: "hover",
tooltip: React37.createElement(TooltipNote, { note: "Create new story with these settings" })
},
React37.createElement(IconButton4, { "aria-label": "Create new story with these settings", onClick: onShowForm }, React37.createElement(AddIcon2, null), React37.createElement(Label5, { "data-short-label": "New" }, "Create new story"))
), React37.createElement(
WithTooltip,
{
as: "div",
hasChrome: false,
trigger: "hover",
tooltip: React37.createElement(TooltipNote, { note: "Reset changes" })
},
React37.createElement(IconButton4, { "aria-label": "Reset changes", onClick: () => resetArgs() }, React37.createElement(UndoIcon2, null), React37.createElement("span", null, "Reset"))
)), React37.createElement(Info, null, React37.createElement(Label5, { "data-short-label": "Unsaved changes" }, "You modified this story. Do you want to save your changes?")), React37.createElement(
Modal,
{
width: 350,
open: creating,
onOpenChange: setCreating,
portalSelector
},
React37.createElement(Form6, { onSubmit: onSubmitForm, id: "create-new-story-form" }, React37.createElement(Modal.Content, null, React37.createElement(Modal.Header, null, React37.createElement(Modal.Title, null, "Create new story"), React37.createElement(Modal.Description, null, "This will add a new story to your existing stories file.")), React37.createElement(
ModalInput,
{
onChange,
placeholder: "Story export name",
readOnly: saving,
ref: inputRef,
value: storyName
}
), React37.createElement(Modal.Actions, null, React37.createElement(Button5, { disabled: saving || !storyName, size: "medium", type: "submit", variant: "solid" }, "Create"), React37.createElement(Modal.Dialog.Close, { asChild: true }, React37.createElement(Button5, { disabled: saving, size: "medium", type: "reset" }, "Cancel"))))),
errorMessage && React37.createElement(Modal.Error, null, errorMessage)
)));
}, "SaveStory");
// src/controls/components/ControlsPanel.tsx
var clean = /* @__PURE__ */ __name((obj) => Object.entries(obj).reduce(
(acc, [key, value2]) => value2 !== void 0 ? Object.assign(acc, { [key]: value2 }) : acc,
{}
), "clean");
var AddonWrapper = styled30.div({
display: "grid",
gridTemplateRows: "1fr 39px",
height: "100%",
maxHeight: "100vh",
overflowY: "auto"
});
var ControlsPanel = /* @__PURE__ */ __name(({ saveStory, createStory }) => {
const api = useStorybookApi();
const [isLoading, setIsLoading] = useState14(true);
const [args, updateArgs, resetArgs, initialArgs] = useArgs();
const [globals] = useGlobals();
const rows = useArgTypes();
const {
expanded,
sort,
presetColors,
disableSaveFromUI = false
} = useParameter(PARAM_KEY5, {});
const { path, previewInitialized } = useStorybookState();
const storyData = api.getCurrentStoryData();
useEffect11(() => {
if (previewInitialized) {
setIsLoading(false);
}
}, [previewInitialized]);
const hasControls = Object.values(rows).some((arg) => arg?.control);
const withPresetColors = Object.entries(rows).reduce((acc, [key, arg]) => {
const control = arg?.control;
if (typeof control !== "object" || control?.type !== "color" || control?.presetColors) {
acc[key] = arg;
} else {
acc[key] = { ...arg, control: { ...control, presetColors } };
}
return acc;
}, {});
const hasUpdatedArgs = useMemo3(
() => !!args && !!initialArgs && !dequal(clean(args), clean(initialArgs)),
[args, initialArgs]
);
return React38.createElement(AddonWrapper, null, React38.createElement(
ArgsTable,
{
key: path,
compact: !expanded && hasControls,
rows: withPresetColors,
args,
globals,
updateArgs,
resetArgs,
inAddonPanel: true,
sort,
isLoading
}
), hasControls && storyData.type === "story" && storyData.subtype !== "test" && hasUpdatedArgs && global.CONFIG_TYPE === "DEVELOPMENT" && disableSaveFromUI !== true && React38.createElement(SaveStory, { ...{ resetArgs, saveStory, createStory } }));
}, "ControlsPanel");
// src/controls/components/Title.tsx
import React39 from "react";
import { Badge } from "storybook/internal/components";
import { useArgTypes as useArgTypes2, useStorybookApi as useStorybookApi2 } from "storybook/manager-api";
function Title2() {
const api = useStorybookApi2();
const selectedPanel = api.getSelectedPanel();
const rows = useArgTypes2();
const controlsCount = Object.values(rows).filter(
(argType) => argType?.control && !argType?.table?.disable
).length;
const suffix = controlsCount === 0 ? null : React39.createElement(Badge, { compact: true, status: selectedPanel === ADDON_ID6 ? "active" : "neutral" }, controlsCount);
return React39.createElement("div", { style: { display: "flex", alignItems: "center", gap: 6 } }, React39.createElement("span", null, "Controls"), suffix);
}
__name(Title2, "Title");
// src/controls/stringifyArgs.tsx
var stringifyArgs = /* @__PURE__ */ __name((args) => JSON.stringify(args, (_2, value2) => {
if (typeof value2 === "function") {
return "__sb_empty_function_arg__";
}
return value2;
}), "stringifyArgs");
// src/controls/manager.tsx
var manager_default = addons.register(ADDON_ID6, (api) => {
if (globalThis?.FEATURES?.controls) {
const channel = addons.getChannel();
const saveStory = /* @__PURE__ */ __name(async () => {
const data = api.getCurrentStoryData();
if (data.type !== "story") {
throw new Error("Not a story");
}
try {
const response = await experimental_requestResponse(channel, SAVE_STORY_REQUEST, SAVE_STORY_RESPONSE, {
// Only send updated args
args: stringifyArgs(
Object.entries(data.args || {}).reduce((acc, [key, value2]) => {
if (!dequal(value2, data.initialArgs?.[key])) {
acc[key] = value2;
}
return acc;
}, {})
),
csfId: data.id,
importPath: data.importPath
});
api.addNotification({
id: "save-story-success",
icon: React40.createElement(PassedIcon, { color: color.positive }),
content: {
headline: "Story saved",
subHeadline: React40.createElement(React40.Fragment, null, "Updated story ", React40.createElement("b", null, response.sourceStoryName), ".")
},
duration: 8e3
});
} catch (error) {
api.addNotification({
id: "save-story-error",
icon: React40.createElement(FailedIcon, { color: color.negative }),
content: {
headline: "Failed to save story",
subHeadline: error?.message || "Check the Storybook process on the command line for more details."
},
duration: 8e3
});
throw error;
}
}, "saveStory");
const createStory = /* @__PURE__ */ __name(async (name) => {
const data = api.getCurrentStoryData();
if (data.type !== "story") {
throw new Error("Not a story");
}
const response = await experimental_requestResponse(channel, SAVE_STORY_REQUEST, SAVE_STORY_RESPONSE, {
args: data.args && stringifyArgs(data.args),
csfId: data.id,
importPath: data.importPath,
name
});
api.addNotification({
id: "save-story-success",
icon: React40.createElement(PassedIcon, { color: color.positive }),
content: {
headline: "Story created",
subHeadline: React40.createElement(React40.Fragment, null, "Added story ", React40.createElement("b", null, response.newStoryName), " based on ", React40.createElement("b", null, response.sourceStoryName), ".")
},
duration: 8e3,
onClick: /* @__PURE__ */ __name(({ onDismiss }) => {
onDismiss();
api.selectStory(response.newStoryId);
}, "onClick")
});
}, "createStory");
addons.add(ADDON_ID6, {
title: Title2,
type: types.PANEL,
paramKey: PARAM_KEY5,
render: /* @__PURE__ */ __name(({ active }) => {
if (!active || !api.getCurrentStoryData()) {
return null;
}
return React40.createElement(AddonPanel, { active }, React40.createElement(ControlsPanel, { saveStory, createStory }));
}, "render")
});
channel.on(SAVE_STORY_RESPONSE, (data) => {
if (!data.success) {
return;
}
const story = api.getCurrentStoryData();
if (story.type !== "story") {
return;
}
api.resetStoryArgs(story);
if (data.payload.newStoryId) {
api.selectStory(data.payload.newStoryId);
}
});
}
});
// src/actions/manager.tsx
import React46 from "react";
import { addons as addons2, types as types2 } from "storybook/manager-api";
// src/actions/components/Title.tsx
import React41 from "react";
import { Badge as Badge2 } from "storybook/internal/components";
import { STORY_CHANGED } from "storybook/internal/core-events";
import { useAddonState, useChannel, useStorybookApi as useStorybookApi3 } from "storybook/manager-api";
function Title3() {
const api = useStorybookApi3();
const selectedPanel = api.getSelectedPanel();
const [{ count }, setCount] = useAddonState(ADDON_ID, { count: 0 });
useChannel({
[EVENT_ID]: () => {
setCount((c2) => ({ ...c2, count: c2.count + 1 }));
},
[STORY_CHANGED]: () => {
setCount((c2) => ({ ...c2, count: 0 }));
},
[CLEAR_ID]: () => {
setCount((c2) => ({ ...c2, count: 0 }));
}
});
const suffix = count === 0 ? null : React41.createElement(Badge2, { compact: true, status: selectedPanel === PANEL_ID ? "active" : "neutral" }, count);
return React41.createElement("div", { style: { display: "flex", alignItems: "center", gap: 6 } }, React41.createElement("span", null, "Actions"), suffix);
}
__name(Title3, "Title");
// src/actions/containers/ActionLogger/index.tsx
import React45, { Component as Component4 } from "react";
import { STORY_CHANGED as STORY_CHANGED2 } from "storybook/internal/core-events";
// src/actions/components/ActionLogger/index.tsx
import React44, { Fragment, forwardRef, useEffect as useEffect12, useRef as useRef6 } from "react";
import { ActionBar as ActionBar2, ScrollArea } from "storybook/internal/components";
// ../node_modules/react-inspector/dist/index.mjs
import React92 from "react";
import React310, { useContext as useContext22, useCallback as useCallback7, useLayoutEffect, useState as useState15, memo as memo2 } from "react";
import { createContext as createContext3 } from "react";
import React210, { Children as Children2, memo } from "react";
import React42, { createContext as createContext22, useContext as useContext3, useMemo as useMemo4 } from "react";
import React72 from "react";
import React43 from "react";
import React62 from "react";
import React52 from "react";
import React82 from "react";
import React132, { useCallback as useCallback32, useState as useState32 } from "react";
import React102 from "react";
import React122 from "react";
import React112, { useCallback as useCallback22, useState as useState22 } from "react";
import React152 from "react";
import React142 from "react";
import React162 from "react";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = /* @__PURE__ */ __name((cb, mod) => /* @__PURE__ */ __name(function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
}, "__require"), "__commonJS");
var __export = /* @__PURE__ */ __name((target, all2) => {
for (var name in all2)
__defProp(target, name, { get: all2[name], enumerable: true });
}, "__export");
var __copyProps = /* @__PURE__ */ __name((to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: /* @__PURE__ */ __name(() => from[key], "get"), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
}, "__copyProps");
var __toESM2 = /* @__PURE__ */ __name((mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)), "__toESM");
var require_is_object = __commonJS({
"node_modules/is-object/index.js"(exports, module) {
"use strict";
module.exports = /* @__PURE__ */ __name(function isObject2(x2) {
return typeof x2 === "object" && x2 !== null;
}, "isObject");
}
});
var require_is_window = __commonJS({
"node_modules/is-window/index.js"(exports, module) {
"use strict";
module.exports = function(obj) {
if (obj == null) {
return false;
}
var o2 = Object(obj);
return o2 === o2.window;
};
}
});
var require_is_dom = __commonJS({
"node_modules/is-dom/index.js"(exports, module) {
var isObject2 = require_is_object();
var isWindow = require_is_window();
function isNode(val) {
if (!isObject2(val) || !isWindow(window) || typeof window.Node !== "function") {
return false;
}
return typeof val.nodeType === "number" && typeof val.nodeName === "string";
}
__name(isNode, "isNode");
module.exports = isNode;
}
});
var themes_exports = {};
__export(themes_exports, {
chromeDark: /* @__PURE__ */ __name(() => theme, "chromeDark"),
chromeLight: /* @__PURE__ */ __name(() => theme2, "chromeLight")
});
var theme = {
BASE_FONT_FAMILY: "Menlo, monospace",
BASE_FONT_SIZE: "11px",
BASE_LINE_HEIGHT: 1.2,
BASE_BACKGROUND_COLOR: "rgb(36, 36, 36)",
BASE_COLOR: "rgb(213, 213, 213)",
OBJECT_PREVIEW_ARRAY_MAX_PROPERTIES: 10,
OBJECT_PREVIEW_OBJECT_MAX_PROPERTIES: 5,
OBJECT_NAME_COLOR: "rgb(227, 110, 236)",
OBJECT_VALUE_NULL_COLOR: "rgb(127, 127, 127)",
OBJECT_VALUE_UNDEFINED_COLOR: "rgb(127, 127, 127)",
OBJECT_VALUE_REGEXP_COLOR: "rgb(233, 63, 59)",
OBJECT_VALUE_STRING_COLOR: "rgb(233, 63, 59)",
OBJECT_VALUE_SYMBOL_COLOR: "rgb(233, 63, 59)",
OBJECT_VALUE_NUMBER_COLOR: "hsl(252, 100%, 75%)",
OBJECT_VALUE_BOOLEAN_COLOR: "hsl(252, 100%, 75%)",
OBJECT_VALUE_FUNCTION_PREFIX_COLOR: "rgb(85, 106, 242)",
HTML_TAG_COLOR: "rgb(93, 176, 215)",
HTML_TAGNAME_COLOR: "rgb(93, 176, 215)",
HTML_TAGNAME_TEXT_TRANSFORM: "lowercase",
HTML_ATTRIBUTE_NAME_COLOR: "rgb(155, 187, 220)",
HTML_ATTRIBUTE_VALUE_COLOR: "rgb(242, 151, 102)",
HTML_COMMENT_COLOR: "rgb(137, 137, 137)",
HTML_DOCTYPE_COLOR: "rgb(192, 192, 192)",
ARROW_COLOR: "rgb(145, 145, 145)",
ARROW_MARGIN_RIGHT: 3,
ARROW_FONT_SIZE: 12,
ARROW_ANIMATION_DURATION: "0",
TREENODE_FONT_FAMILY: "Menlo, monospace",
TREENODE_FONT_SIZE: "11px",
TREENODE_LINE_HEIGHT: 1.2,
TREENODE_PADDING_LEFT: 12,
TABLE_BORDER_COLOR: "rgb(85, 85, 85)",
TABLE_TH_BACKGROUND_COLOR: "rgb(44, 44, 44)",
TABLE_TH_HOVER_COLOR: "rgb(48, 48, 48)",
TABLE_SORT_ICON_COLOR: "black",
TABLE_DATA_BACKGROUND_IMAGE: "linear-gradient(rgba(255, 255, 255, 0), rgba(255, 255, 255, 0) 50%, rgba(51, 139, 255, 0.0980392) 50%, rgba(51, 139, 255, 0.0980392))",
TABLE_DATA_BACKGROUND_SIZE: "128px 32px"
};
var theme2 = {
BASE_FONT_FAMILY: "Menlo, monospace",
BASE_FONT_SIZE: "11px",
BASE_LINE_HEIGHT: 1.2,
BASE_BACKGROUND_COLOR: "white",
BASE_COLOR: "black",
OBJECT_PREVIEW_ARRAY_MAX_PROPERTIES: 10,
OBJECT_PREVIEW_OBJECT_MAX_PROPERTIES: 5,
OBJECT_NAME_COLOR: "rgb(136, 19, 145)",
OBJECT_VALUE_NULL_COLOR: "rgb(128, 128, 128)",
OBJECT_VALUE_UNDEFINED_COLOR: "rgb(128, 128, 128)",
OBJECT_VALUE_REGEXP_COLOR: "rgb(196, 26, 22)",
OBJECT_VALUE_STRING_COLOR: "rgb(196, 26, 22)",
OBJECT_VALUE_SYMBOL_COLOR: "rgb(196, 26, 22)",
OBJECT_VALUE_NUMBER_COLOR: "rgb(28, 0, 207)",
OBJECT_VALUE_BOOLEAN_COLOR: "rgb(28, 0, 207)",
OBJECT_VALUE_FUNCTION_PREFIX_COLOR: "rgb(13, 34, 170)",
HTML_TAG_COLOR: "rgb(168, 148, 166)",
HTML_TAGNAME_COLOR: "rgb(136, 18, 128)",
HTML_TAGNAME_TEXT_TRANSFORM: "lowercase",
HTML_ATTRIBUTE_NAME_COLOR: "rgb(153, 69, 0)",
HTML_ATTRIBUTE_VALUE_COLOR: "rgb(26, 26, 166)",
HTML_COMMENT_COLOR: "rgb(35, 110, 37)",
HTML_DOCTYPE_COLOR: "rgb(192, 192, 192)",
ARROW_COLOR: "#6e6e6e",
ARROW_MARGIN_RIGHT: 3,
ARROW_FONT_SIZE: 12,
ARROW_ANIMATION_DURATION: "0",
TREENODE_FONT_FAMILY: "Menlo, monospace",
TREENODE_FONT_SIZE: "11px",
TREENODE_LINE_HEIGHT: 1.2,
TREENODE_PADDING_LEFT: 12,
TABLE_BORDER_COLOR: "#aaa",
TABLE_TH_BACKGROUND_COLOR: "#eee",
TABLE_TH_HOVER_COLOR: "hsla(0, 0%, 90%, 1)",
TABLE_SORT_ICON_COLOR: "#6e6e6e",
TABLE_DATA_BACKGROUND_IMAGE: "linear-gradient(to bottom, white, white 50%, rgb(234, 243, 255) 50%, rgb(234, 243, 255))",
TABLE_DATA_BACKGROUND_SIZE: "128px 32px"
};
var ExpandedPathsContext = createContext3([{}, () => {
}]);
var unselectable = {
WebkitTouchCallout: "none",
WebkitUserSelect: "none",
KhtmlUserSelect: "none",
MozUserSelect: "none",
msUserSelect: "none",
OUserSelect: "none",
userSelect: "none"
};
var createTheme = /* @__PURE__ */ __name((theme3) => ({
DOMNodePreview: {
htmlOpenTag: {
base: {
color: theme3.HTML_TAG_COLOR
},
tagName: {
color: theme3.HTML_TAGNAME_COLOR,
textTransform: theme3.HTML_TAGNAME_TEXT_TRANSFORM
},
htmlAttributeName: {
color: theme3.HTML_ATTRIBUTE_NAME_COLOR
},
htmlAttributeValue: {
color: theme3.HTML_ATTRIBUTE_VALUE_COLOR
}
},
htmlCloseTag: {
base: {
color: theme3.HTML_TAG_COLOR
},
offsetLeft: {
marginLeft: -theme3.TREENODE_PADDING_LEFT
},
tagName: {
color: theme3.HTML_TAGNAME_COLOR,
textTransform: theme3.HTML_TAGNAME_TEXT_TRANSFORM
}
},
htmlComment: {
color: theme3.HTML_COMMENT_COLOR
},
htmlDoctype: {
color: theme3.HTML_DOCTYPE_COLOR
}
},
ObjectPreview: {
objectDescription: {
fontStyle: "italic"
},
preview: {
fontStyle: "italic"
},
arrayMaxProperties: theme3.OBJECT_PREVIEW_ARRAY_MAX_PROPERTIES,
objectMaxProperties: theme3.OBJECT_PREVIEW_OBJECT_MAX_PROPERTIES
},
ObjectName: {
base: {
color: theme3.OBJECT_NAME_COLOR
},
dimmed: {
opacity: 0.6
}
},
ObjectValue: {
objectValueNull: {
color: theme3.OBJECT_VALUE_NULL_COLOR
},
objectValueUndefined: {
color: theme3.OBJECT_VALUE_UNDEFINED_COLOR
},
objectValueRegExp: {
color: theme3.OBJECT_VALUE_REGEXP_COLOR
},
objectValueString: {
color: theme3.OBJECT_VALUE_STRING_COLOR
},
objectValueSymbol: {
color: theme3.OBJECT_VALUE_SYMBOL_COLOR
},
objectValueNumber: {
color: theme3.OBJECT_VALUE_NUMBER_COLOR
},
objectValueBoolean: {
color: theme3.OBJECT_VALUE_BOOLEAN_COLOR
},
objectValueFunctionPrefix: {
color: theme3.OBJECT_VALUE_FUNCTION_PREFIX_COLOR,
fontStyle: "italic"
},
objectValueFunctionName: {
fontStyle: "italic"
}
},
TreeView: {
treeViewOutline: {
padding: 0,
margin: 0,
listStyleType: "none"
}
},
TreeNode: {
treeNodeBase: {
color: theme3.BASE_COLOR,
backgroundColor: theme3.BASE_BACKGROUND_COLOR,
lineHeight: theme3.TREENODE_LINE_HEIGHT,
cursor: "default",
boxSizing: "border-box",
listStyle: "none",
fontFamily: theme3.TREENODE_FONT_FAMILY,
fontSize: theme3.TREENODE_FONT_SIZE
},
treeNodePreviewContainer: {},
treeNodePlaceholder: {
whiteSpace: "pre",
fontSize: theme3.ARROW_FONT_SIZE,
marginRight: theme3.ARROW_MARGIN_RIGHT,
...unselectable
},
treeNodeArrow: {
base: {
color: theme3.ARROW_COLOR,
display: "inline-block",
fontSize: theme3.ARROW_FONT_SIZE,
marginRight: theme3.ARROW_MARGIN_RIGHT,
...parseFloat(theme3.ARROW_ANIMATION_DURATION) > 0 ? {
transition: `transform ${theme3.ARROW_ANIMATION_DURATION} ease 0s`
} : {},
...unselectable
},
expanded: {
WebkitTransform: "rotateZ(90deg)",
MozTransform: "rotateZ(90deg)",
transform: "rotateZ(90deg)"
},
collapsed: {
WebkitTransform: "rotateZ(0deg)",
MozTransform: "rotateZ(0deg)",
transform: "rotateZ(0deg)"
}
},
treeNodeChildNodesContainer: {
margin: 0,
paddingLeft: theme3.TREENODE_PADDING_LEFT
}
},
TableInspector: {
base: {
color: theme3.BASE_COLOR,
position: "relative",
border: `1px solid ${theme3.TABLE_BORDER_COLOR}`,
fontFamily: theme3.BASE_FONT_FAMILY,
fontSize: theme3.BASE_FONT_SIZE,
lineHeight: "120%",
boxSizing: "border-box",
cursor: "default"
}
},
TableInspectorHeaderContainer: {
base: {
top: 0,
height: "17px",
left: 0,
right: 0,
overflowX: "hidden"
},
table: {
tableLayout: "fixed",
borderSpacing: 0,
borderCollapse: "separate",
height: "100%",
width: "100%",
margin: 0
}
},
TableInspectorDataContainer: {
tr: {
display: "table-row"
},
td: {
boxSizing: "border-box",
border: "none",
height: "16px",
verticalAlign: "top",
padding: "1px 4px",
WebkitUserSelect: "text",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
overflow: "hidden",
lineHeight: "14px"
},
div: {
position: "static",
top: "17px",
bottom: 0,
overflowY: "overlay",
transform: "translateZ(0)",
left: 0,
right: 0,
overflowX: "hidden"
},
table: {
positon: "static",
left: 0,
top: 0,
right: 0,
bottom: 0,
borderTop: "0 none transparent",
margin: 0,
backgroundImage: theme3.TABLE_DATA_BACKGROUND_IMAGE,
backgroundSize: theme3.TABLE_DATA_BACKGROUND_SIZE,
tableLayout: "fixed",
borderSpacing: 0,
borderCollapse: "separate",
width: "100%",
fontSize: theme3.BASE_FONT_SIZE,
lineHeight: "120%"
}
},
TableInspectorTH: {
base: {
position: "relative",
height: "auto",
textAlign: "left",
backgroundColor: theme3.TABLE_TH_BACKGROUND_COLOR,
borderBottom: `1px solid ${theme3.TABLE_BORDER_COLOR}`,
fontWeight: "normal",
verticalAlign: "middle",
padding: "0 4px",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
overflow: "hidden",
lineHeight: "14px",
":hover": {
backgroundColor: theme3.TABLE_TH_HOVER_COLOR
}
},
div: {
whiteSpace: "nowrap",
textOverflow: "ellipsis",
overflow: "hidden",
fontSize: theme3.BASE_FONT_SIZE,
lineHeight: "120%"
}
},
TableInspectorLeftBorder: {
none: {
borderLeft: "none"
},
solid: {
borderLeft: `1px solid ${theme3.TABLE_BORDER_COLOR}`
}
},
TableInspectorSortIcon: {
display: "block",
marginRight: 3,
width: 8,
height: 7,
marginTop: -7,
color: theme3.TABLE_SORT_ICON_COLOR,
fontSize: 12,
...unselectable
}
}), "createTheme");
var DEFAULT_THEME_NAME = "chromeLight";
var ThemeContext = createContext22(createTheme(themes_exports[DEFAULT_THEME_NAME]));
var useStyles = /* @__PURE__ */ __name((baseStylesKey) => {
const themeStyles = useContext3(ThemeContext);
return themeStyles[baseStylesKey];
}, "useStyles");
var themeAcceptor = /* @__PURE__ */ __name((WrappedComponent) => {
const ThemeAcceptor = /* @__PURE__ */ __name(({ theme: theme3 = DEFAULT_THEME_NAME, ...restProps }) => {
const themeStyles = useMemo4(() => {
switch (Object.prototype.toString.call(theme3)) {
case "[object String]":
return createTheme(themes_exports[theme3]);
case "[object Object]":
return createTheme(theme3);
default:
return createTheme(themes_exports[DEFAULT_THEME_NAME]);
}
}, [theme3]);
return React42.createElement(ThemeContext.Provider, {
value: themeStyles
}, React42.createElement(WrappedComponent, {
...restProps
}));
}, "ThemeAcceptor");
return ThemeAcceptor;
}, "themeAcceptor");
var Arrow = /* @__PURE__ */ __name(({ expanded, styles }) => React210.createElement("span", {
style: {
...styles.base,
...expanded ? styles.expanded : styles.collapsed
}
}, "\u25B6"), "Arrow");
var TreeNode = memo((props) => {
props = {
expanded: true,
nodeRenderer: /* @__PURE__ */ __name(({ name }) => React210.createElement("span", null, name), "nodeRenderer"),
onClick: /* @__PURE__ */ __name(() => {
}, "onClick"),
shouldShowArrow: false,
shouldShowPlaceholder: true,
...props
};
const { expanded, onClick, children, nodeRenderer, title, shouldShowArrow, shouldShowPlaceholder } = props;
const styles = useStyles("TreeNode");
const NodeRenderer = nodeRenderer;
return React210.createElement("li", {
"aria-expanded": expanded,
role: "treeitem",
style: styles.treeNodeBase,
title
}, React210.createElement("div", {
style: styles.treeNodePreviewContainer,
onClick
}, shouldShowArrow || Children2.count(children) > 0 ? React210.createElement(Arrow, {
expanded,
styles: styles.treeNodeArrow
}) : shouldShowPlaceholder && React210.createElement("span", {
style: styles.treeNodePlaceholder
}, "\xA0"), React210.createElement(NodeRenderer, {
...props
})), React210.createElement("ol", {
role: "group",
style: styles.treeNodeChildNodesContainer
}, expanded ? children : void 0));
});
var DEFAULT_ROOT_PATH = "$";
var WILDCARD = "*";
function hasChildNodes(data, dataIterator) {
return !dataIterator(data).next().done;
}
__name(hasChildNodes, "hasChildNodes");
var wildcardPathsFromLevel = /* @__PURE__ */ __name((level) => {
return Array.from({ length: level }, (_2, i2) => [DEFAULT_ROOT_PATH].concat(Array.from({ length: i2 }, () => "*")).join("."));
}, "wildcardPathsFromLevel");
var getExpandedPaths = /* @__PURE__ */ __name((data, dataIterator, expandPaths, expandLevel, prevExpandedPaths) => {
const wildcardPaths = [].concat(wildcardPathsFromLevel(expandLevel)).concat(expandPaths).filter((path) => typeof path === "string");
const expandedPaths = [];
wildcardPaths.forEach((wildcardPath) => {
const keyPaths = wildcardPath.split(".");
const populatePaths = /* @__PURE__ */ __name((curData, curPath, depth) => {
if (depth === keyPaths.length) {
expandedPaths.push(curPath);
return;
}
const key = keyPaths[depth];
if (depth === 0) {
if (hasChildNodes(curData, dataIterator) && (key === DEFAULT_ROOT_PATH || key === WILDCARD)) {
populatePaths(curData, DEFAULT_ROOT_PATH, depth + 1);
}
} else {
if (key === WILDCARD) {
for (const { name, data: data2 } of dataIterator(curData)) {
if (hasChildNodes(data2, dataIterator)) {
populatePaths(data2, `${curPath}.${name}`, depth + 1);
}
}
} else {
const value2 = curData[key];
if (hasChildNodes(value2, dataIterator)) {
populatePaths(value2, `${curPath}.${key}`, depth + 1);
}
}
}
}, "populatePaths");
populatePaths(data, "", 0);
});
return expandedPaths.reduce((obj, path) => {
obj[path] = true;
return obj;
}, { ...prevExpandedPaths });
}, "getExpandedPaths");
var ConnectedTreeNode = memo2((props) => {
const { data, dataIterator, path, depth, nodeRenderer } = props;
const [expandedPaths, setExpandedPaths] = useContext22(ExpandedPathsContext);
const nodeHasChildNodes = hasChildNodes(data, dataIterator);
const expanded = !!expandedPaths[path];
const handleClick = useCallback7(() => nodeHasChildNodes && setExpandedPaths((prevExpandedPaths) => ({
...prevExpandedPaths,
[path]: !expanded
})), [nodeHasChildNodes, setExpandedPaths, path, expanded]);
return React310.createElement(TreeNode, {
expanded,
onClick: handleClick,
shouldShowArrow: nodeHasChildNodes,
shouldShowPlaceholder: depth > 0,
nodeRenderer,
...props
}, expanded ? [...dataIterator(data)].map(({ name, data: data2, ...renderNodeProps }) => {
return React310.createElement(ConnectedTreeNode, {
name,
data: data2,
depth: depth + 1,
path: `${path}.${name}`,
key: name,
dataIterator,
nodeRenderer,
...renderNodeProps
});
}) : null);
});
var TreeView = memo2(({ name, data, dataIterator, nodeRenderer, expandPaths, expandLevel }) => {
const styles = useStyles("TreeView");
const stateAndSetter = useState15({});
const [, setExpandedPaths] = stateAndSetter;
useLayoutEffect(() => setExpandedPaths((prevExpandedPaths) => getExpandedPaths(data, dataIterator, expandPaths, expandLevel, prevExpandedPaths)), [data, dataIterator, expandPaths, expandLevel]);
return React310.createElement(ExpandedPathsContext.Provider, {
value: stateAndSetter
}, React310.createElement("ol", {
role: "tree",
style: styles.treeViewOutline
}, React310.createElement(ConnectedTreeNode, {
name,
data,
dataIterator,
depth: 0,
path: DEFAULT_ROOT_PATH,
nodeRenderer
})));
});
var ObjectName = /* @__PURE__ */ __name(({ name, dimmed = false, styles = {} }) => {
const themeStyles = useStyles("ObjectName");
const appliedStyles = {
...themeStyles.base,
...dimmed ? themeStyles["dimmed"] : {},
...styles
};
return React43.createElement("span", {
style: appliedStyles
}, name);
}, "ObjectName");
var ObjectValue = /* @__PURE__ */ __name(({ object: object2, styles }) => {
const themeStyles = useStyles("ObjectValue");
const mkStyle = /* @__PURE__ */ __name((key) => ({ ...themeStyles[key], ...styles }), "mkStyle");
switch (typeof object2) {
case "bigint":
return React52.createElement("span", {
style: mkStyle("objectValueNumber")
}, String(object2), "n");
case "number":
return React52.createElement("span", {
style: mkStyle("objectValueNumber")
}, String(object2));
case "string":
return React52.createElement("span", {
style: mkStyle("objectValueString")
}, '"', object2, '"');
case "boolean":
return React52.createElement("span", {
style: mkStyle("objectValueBoolean")
}, String(object2));
case "undefined":
return React52.createElement("span", {
style: mkStyle("objectValueUndefined")
}, "undefined");
case "object":
if (object2 === null) {
return React52.createElement("span", {
style: mkStyle("objectValueNull")
}, "null");
}
if (object2 instanceof Date) {
return React52.createElement("span", null, object2.toString());
}
if (object2 instanceof RegExp) {
return React52.createElement("span", {
style: mkStyle("objectValueRegExp")
}, object2.toString());
}
if (Array.isArray(object2)) {
return React52.createElement("span", null, `Array(${object2.length})`);
}
if (!object2.constructor) {
return React52.createElement("span", null, "Object");
}
if (typeof object2.constructor.isBuffer === "function" && object2.constructor.isBuffer(object2)) {
return React52.createElement("span", null, `Buffer[${object2.length}]`);
}
return React52.createElement("span", null, object2.constructor.name);
case "function":
return React52.createElement("span", null, React52.createElement("span", {
style: mkStyle("objectValueFunctionPrefix")
}, "\u0192\xA0"), React52.createElement("span", {
style: mkStyle("objectValueFunctionName")
}, object2.name, "()"));
case "symbol":
return React52.createElement("span", {
style: mkStyle("objectValueSymbol")
}, object2.toString());
default:
return React52.createElement("span", null);
}
}, "ObjectValue");
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
function getPropertyValue(object2, propertyName) {
const propertyDescriptor = Object.getOwnPropertyDescriptor(object2, propertyName);
if (propertyDescriptor.get) {
try {
return propertyDescriptor.get();
} catch {
return propertyDescriptor.get;
}
}
return object2[propertyName];
}
__name(getPropertyValue, "getPropertyValue");
function intersperse(arr, sep) {
if (arr.length === 0) {
return [];
}
return arr.slice(1).reduce((xs, x2) => xs.concat([sep, x2]), [arr[0]]);
}
__name(intersperse, "intersperse");
var ObjectPreview = /* @__PURE__ */ __name(({ data }) => {
const styles = useStyles("ObjectPreview");
const object2 = data;
if (typeof object2 !== "object" || object2 === null || object2 instanceof Date || object2 instanceof RegExp) {
return React62.createElement(ObjectValue, {
object: object2
});
}
if (Array.isArray(object2)) {
const maxProperties = styles.arrayMaxProperties;
const previewArray = object2.slice(0, maxProperties).map((element, index) => React62.createElement(ObjectValue, {
key: index,
object: element
}));
if (object2.length > maxProperties) {
previewArray.push(React62.createElement("span", {
key: "ellipsis"
}, "\u2026"));
}
const arrayLength = object2.length;
return React62.createElement(React62.Fragment, null, React62.createElement("span", {
style: styles.objectDescription
}, arrayLength === 0 ? `` : `(${arrayLength})\xA0`), React62.createElement("span", {
style: styles.preview
}, "[", intersperse(previewArray, ", "), "]"));
} else {
const maxProperties = styles.objectMaxProperties;
const propertyNodes = [];
for (const propertyName in object2) {
if (hasOwnProperty.call(object2, propertyName)) {
let ellipsis;
if (propertyNodes.length === maxProperties - 1 && Object.keys(object2).length > maxProperties) {
ellipsis = React62.createElement("span", {
key: "ellipsis"
}, "\u2026");
}
const propertyValue = getPropertyValue(object2, propertyName);
propertyNodes.push(React62.createElement("span", {
key: propertyName
}, React62.createElement(ObjectName, {
name: propertyName || `""`
}), ":\xA0", React62.createElement(ObjectValue, {
object: propertyValue
}), ellipsis));
if (ellipsis)
break;
}
}
const objectConstructorName = object2.constructor ? object2.constructor.name : "Object";
return React62.createElement(React62.Fragment, null, React62.createElement("span", {
style: styles.objectDescription
}, objectConstructorName === "Object" ? "" : `${objectConstructorName} `), React62.createElement("span", {
style: styles.preview
}, "{", intersperse(propertyNodes, ", "), "}"));
}
}, "ObjectPreview");
var ObjectRootLabel = /* @__PURE__ */ __name(({ name, data }) => {
if (typeof name === "string") {
return React72.createElement("span", null, React72.createElement(ObjectName, {
name
}), React72.createElement("span", null, ": "), React72.createElement(ObjectPreview, {
data
}));
} else {
return React72.createElement(ObjectPreview, {
data
});
}
}, "ObjectRootLabel");
var ObjectLabel = /* @__PURE__ */ __name(({ name, data, isNonenumerable = false }) => {
const object2 = data;
return React82.createElement("span", null, typeof name === "string" ? React82.createElement(ObjectName, {
name,
dimmed: isNonenumerable
}) : React82.createElement(ObjectPreview, {
data: name
}), React82.createElement("span", null, ": "), React82.createElement(ObjectValue, {
object: object2
}));
}, "ObjectLabel");
var createIterator = /* @__PURE__ */ __name((showNonenumerable, sortObjectKeys) => {
const objectIterator = /* @__PURE__ */ __name(function* (data) {
const shouldIterate = typeof data === "object" && data !== null || typeof data === "function";
if (!shouldIterate)
return;
const dataIsArray = Array.isArray(data);
if (!dataIsArray && data[Symbol.iterator]) {
let i2 = 0;
for (const entry of data) {
if (Array.isArray(entry) && entry.length === 2) {
const [k2, v2] = entry;
yield {
name: k2,
data: v2
};
} else {
yield {
name: i2.toString(),
data: entry
};
}
i2++;
}
} else {
const keys = Object.getOwnPropertyNames(data);
if (sortObjectKeys === true && !dataIsArray) {
keys.sort();
} else if (typeof sortObjectKeys === "function") {
keys.sort(sortObjectKeys);
}
for (const propertyName of keys) {
if (propertyIsEnumerable.call(data, propertyName)) {
const propertyValue = getPropertyValue(data, propertyName);
yield {
name: propertyName || `""`,
data: propertyValue
};
} else if (showNonenumerable) {
let propertyValue;
try {
propertyValue = getPropertyValue(data, propertyName);
} catch (e2) {
}
if (propertyValue !== void 0) {
yield {
name: propertyName,
data: propertyValue,
isNonenumerable: true
};
}
}
}
if (showNonenumerable && data !== Object.prototype) {
yield {
name: "__proto__",
data: Object.getPrototypeOf(data),
isNonenumerable: true
};
}
}
}, "objectIterator");
return objectIterator;
}, "createIterator");
var defaultNodeRenderer = /* @__PURE__ */ __name(({ depth, name, data, isNonenumerable }) => depth === 0 ? React92.createElement(ObjectRootLabel, {
name,
data
}) : React92.createElement(ObjectLabel, {
name,
data,
isNonenumerable
}), "defaultNodeRenderer");
var ObjectInspector = /* @__PURE__ */ __name(({ showNonenumerable = false, sortObjectKeys, nodeRenderer, ...treeViewProps }) => {
const dataIterator = createIterator(showNonenumerable, sortObjectKeys);
const renderer = nodeRenderer ? nodeRenderer : defaultNodeRenderer;
return React92.createElement(TreeView, {
nodeRenderer: renderer,
dataIterator,
...treeViewProps
});
}, "ObjectInspector");
var themedObjectInspector = themeAcceptor(ObjectInspector);
function getHeaders(data) {
if (typeof data === "object") {
let rowHeaders = [];
if (Array.isArray(data)) {
const nRows = data.length;
rowHeaders = [...Array(nRows).keys()];
} else if (data !== null) {
rowHeaders = Object.keys(data);
}
const colHeaders = rowHeaders.reduce((colHeaders2, rowHeader) => {
const row = data[rowHeader];
if (typeof row === "object" && row !== null) {
const cols = Object.keys(row);
cols.reduce((xs, x2) => {
if (!xs.includes(x2)) {
xs.push(x2);
}
return xs;
}, colHeaders2);
}
return colHeaders2;
}, []);
return {
rowHeaders,
colHeaders
};
}
return void 0;
}
__name(getHeaders, "getHeaders");
var DataContainer = /* @__PURE__ */ __name(({ rows, columns, rowsData }) => {
const styles = useStyles("TableInspectorDataContainer");
const borderStyles = useStyles("TableInspectorLeftBorder");
return React102.createElement("div", {
style: styles.div
}, React102.createElement("table", {
style: styles.table
}, React102.createElement("colgroup", null), React102.createElement("tbody", null, rows.map((row, i2) => React102.createElement("tr", {
key: row,
style: styles.tr
}, React102.createElement("td", {
style: { ...styles.td, ...borderStyles.none }
}, row), columns.map((column) => {
const rowData = rowsData[i2];
if (typeof rowData === "object" && rowData !== null && hasOwnProperty.call(rowData, column)) {
return React102.createElement("td", {
key: column,
style: { ...styles.td, ...borderStyles.solid }
}, React102.createElement(ObjectValue, {
object: rowData[column]
}));
} else {
return React102.createElement("td", {
key: column,
style: { ...styles.td, ...borderStyles.solid }
});
}
}))))));
}, "DataContainer");
var SortIconContainer = /* @__PURE__ */ __name((props) => React112.createElement("div", {
style: {
position: "absolute",
top: 1,
right: 0,
bottom: 1,
display: "flex",
alignItems: "center"
}
}, props.children), "SortIconContainer");
var SortIcon = /* @__PURE__ */ __name(({ sortAscending }) => {
const styles = useStyles("TableInspectorSortIcon");
const glyph = sortAscending ? "\u25B2" : "\u25BC";
return React112.createElement("div", {
style: styles
}, glyph);
}, "SortIcon");
var TH = /* @__PURE__ */ __name(({
sortAscending = false,
sorted = false,
onClick = void 0,
borderStyle = {},
children,
...thProps
}) => {
const styles = useStyles("TableInspectorTH");
const [hovered, setHovered] = useState22(false);
const handleMouseEnter = useCallback22(() => setHovered(true), []);
const handleMouseLeave = useCallback22(() => setHovered(false), []);
return React112.createElement("th", {
...thProps,
style: {
...styles.base,
...borderStyle,
...hovered ? styles.base[":hover"] : {}
},
onMouseEnter: handleMouseEnter,
onMouseLeave: handleMouseLeave,
onClick
}, React112.createElement("div", {
style: styles.div
}, children), sorted && React112.createElement(SortIconContainer, null, React112.createElement(SortIcon, {
sortAscending
})));
}, "TH");
var HeaderContainer = /* @__PURE__ */ __name(({
indexColumnText = "(index)",
columns = [],
sorted,
sortIndexColumn,
sortColumn,
sortAscending,
onTHClick,
onIndexTHClick
}) => {
const styles = useStyles("TableInspectorHeaderContainer");
const borderStyles = useStyles("TableInspectorLeftBorder");
return React122.createElement("div", {
style: styles.base
}, React122.createElement("table", {
style: styles.table
}, React122.createElement("tbody", null, React122.createElement("tr", null, React122.createElement(TH, {
borderStyle: borderStyles.none,
sorted: sorted && sortIndexColumn,
sortAscending,
onClick: onIndexTHClick
}, indexColumnText), columns.map((column) => React122.createElement(TH, {
borderStyle: borderStyles.solid,
key: column,
sorted: sorted && sortColumn === column,
sortAscending,
onClick: onTHClick.bind(null, column)
}, column))))));
}, "HeaderContainer");
var TableInspector = /* @__PURE__ */ __name(({
data,
columns
}) => {
const styles = useStyles("TableInspector");
const [{ sorted, sortIndexColumn, sortColumn, sortAscending }, setState] = useState32({
sorted: false,
sortIndexColumn: false,
sortColumn: void 0,
sortAscending: false
});
const handleIndexTHClick = useCallback32(() => {
setState(({ sortIndexColumn: sortIndexColumn2, sortAscending: sortAscending2 }) => ({
sorted: true,
sortIndexColumn: true,
sortColumn: void 0,
sortAscending: sortIndexColumn2 ? !sortAscending2 : true
}));
}, []);
const handleTHClick = useCallback32((col) => {
setState(({ sortColumn: sortColumn2, sortAscending: sortAscending2 }) => ({
sorted: true,
sortIndexColumn: false,
sortColumn: col,
sortAscending: col === sortColumn2 ? !sortAscending2 : true
}));
}, []);
if (typeof data !== "object" || data === null) {
return React132.createElement("div", null);
}
let { rowHeaders, colHeaders } = getHeaders(data);
if (columns !== void 0) {
colHeaders = columns;
}
let rowsData = rowHeaders.map((rowHeader) => data[rowHeader]);
let columnDataWithRowIndexes;
if (sortColumn !== void 0) {
columnDataWithRowIndexes = rowsData.map((rowData, index) => {
if (typeof rowData === "object" && rowData !== null) {
const columnData = rowData[sortColumn];
return [columnData, index];
}
return [void 0, index];
});
} else {
if (sortIndexColumn) {
columnDataWithRowIndexes = rowHeaders.map((rowData, index) => {
const columnData = rowHeaders[index];
return [columnData, index];
});
}
}
if (columnDataWithRowIndexes !== void 0) {
const comparator = /* @__PURE__ */ __name((mapper, ascending) => {
return (a2, b2) => {
const v1 = mapper(a2);
const v2 = mapper(b2);
const type1 = typeof v1;
const type2 = typeof v2;
const lt = /* @__PURE__ */ __name((v12, v22) => {
if (v12 < v22) {
return -1;
} else if (v12 > v22) {
return 1;
} else {
return 0;
}
}, "lt");
let result;
if (type1 === type2) {
result = lt(v1, v2);
} else {
const order = {
string: 0,
number: 1,
object: 2,
symbol: 3,
boolean: 4,
undefined: 5,
function: 6
};
result = lt(order[type1], order[type2]);
}
if (!ascending)
result = -result;
return result;
};
}, "comparator");
const sortedRowIndexes = columnDataWithRowIndexes.sort(comparator((item) => item[0], sortAscending)).map((item) => item[1]);
rowHeaders = sortedRowIndexes.map((i2) => rowHeaders[i2]);
rowsData = sortedRowIndexes.map((i2) => rowsData[i2]);
}
return React132.createElement("div", {
style: styles.base
}, React132.createElement(HeaderContainer, {
columns: colHeaders,
sorted,
sortIndexColumn,
sortColumn,
sortAscending,
onTHClick: handleTHClick,
onIndexTHClick: handleIndexTHClick
}), React132.createElement(DataContainer, {
rows: rowHeaders,
columns: colHeaders,
rowsData
}));
}, "TableInspector");
var themedTableInspector = themeAcceptor(TableInspector);
var TEXT_NODE_MAX_INLINE_CHARS = 80;
var shouldInline = /* @__PURE__ */ __name((data) => data.childNodes.length === 0 || data.childNodes.length === 1 && data.childNodes[0].nodeType === Node.TEXT_NODE && data.textContent.length < TEXT_NODE_MAX_INLINE_CHARS, "shouldInline");
var OpenTag = /* @__PURE__ */ __name(({ tagName, attributes, styles }) => {
return React142.createElement("span", {
style: styles.base
}, "<", React142.createElement("span", {
style: styles.tagName
}, tagName), (() => {
if (attributes) {
const attributeNodes = [];
for (let i2 = 0; i2 < attributes.length; i2++) {
const attribute = attributes[i2];
attributeNodes.push(React142.createElement("span", {
key: i2
}, " ", React142.createElement("span", {
style: styles.htmlAttributeName
}, attribute.name), '="', React142.createElement("span", {
style: styles.htmlAttributeValue
}, attribute.value), '"'));
}
return attributeNodes;
}
})(), ">");
}, "OpenTag");
var CloseTag = /* @__PURE__ */ __name(({ tagName, isChildNode = false, styles }) => React142.createElement("span", {
style: Object.assign({}, styles.base, isChildNode && styles.offsetLeft)
}, "</", React142.createElement("span", {
style: styles.tagName
}, tagName), ">"), "CloseTag");
var nameByNodeType = {
1: "ELEMENT_NODE",
3: "TEXT_NODE",
7: "PROCESSING_INSTRUCTION_NODE",
8: "COMMENT_NODE",
9: "DOCUMENT_NODE",
10: "DOCUMENT_TYPE_NODE",
11: "DOCUMENT_FRAGMENT_NODE"
};
var DOMNodePreview = /* @__PURE__ */ __name(({ isCloseTag, data, expanded }) => {
const styles = useStyles("DOMNodePreview");
if (isCloseTag) {
return React142.createElement(CloseTag, {
styles: styles.htmlCloseTag,
isChildNode: true,
tagName: data.tagName
});
}
switch (data.nodeType) {
case Node.ELEMENT_NODE:
return React142.createElement("span", null, React142.createElement(OpenTag, {
tagName: data.tagName,
attributes: data.attributes,
styles: styles.htmlOpenTag
}), shouldInline(data) ? data.textContent : !expanded && "\u2026", !expanded && React142.createElement(CloseTag, {
tagName: data.tagName,
styles: styles.htmlCloseTag
}));
case Node.TEXT_NODE:
return React142.createElement("span", null, data.textContent);
case Node.CDATA_SECTION_NODE:
return React142.createElement("span", null, "<![CDATA[" + data.textContent + "]]>");
case Node.COMMENT_NODE:
return React142.createElement("span", {
style: styles.htmlComment
}, "<!--", data.textContent, "-->");
case Node.PROCESSING_INSTRUCTION_NODE:
return React142.createElement("span", null, data.nodeName);
case Node.DOCUMENT_TYPE_NODE:
return React142.createElement("span", {
style: styles.htmlDoctype
}, "<!DOCTYPE ", data.name, data.publicId ? ` PUBLIC "${data.publicId}"` : "", !data.publicId && data.systemId ? " SYSTEM" : "", data.systemId ? ` "${data.systemId}"` : "", ">");
case Node.DOCUMENT_NODE:
return React142.createElement("span", null, data.nodeName);
case Node.DOCUMENT_FRAGMENT_NODE:
return React142.createElement("span", null, data.nodeName);
default:
return React142.createElement("span", null, nameByNodeType[data.nodeType]);
}
}, "DOMNodePreview");
var domIterator = /* @__PURE__ */ __name(function* (data) {
if (data && data.childNodes) {
const textInlined = shouldInline(data);
if (textInlined) {
return;
}
for (let i2 = 0; i2 < data.childNodes.length; i2++) {
const node = data.childNodes[i2];
if (node.nodeType === Node.TEXT_NODE && node.textContent.trim().length === 0)
continue;
yield {
name: `${node.tagName}[${i2}]`,
data: node
};
}
if (data.tagName) {
yield {
name: "CLOSE_TAG",
data: {
tagName: data.tagName
},
isCloseTag: true
};
}
}
}, "domIterator");
var DOMInspector = /* @__PURE__ */ __name((props) => {
return React152.createElement(TreeView, {
nodeRenderer: DOMNodePreview,
dataIterator: domIterator,
...props
});
}, "DOMInspector");
var themedDOMInspector = themeAcceptor(DOMInspector);
var import_is_dom = __toESM2(require_is_dom());
var Inspector = /* @__PURE__ */ __name(({ table = false, data, ...rest }) => {
if (table) {
return React162.createElement(themedTableInspector, {
data,
...rest
});
}
if ((0, import_is_dom.default)(data))
return React162.createElement(themedDOMInspector, {
data,
...rest
});
return React162.createElement(themedObjectInspector, {
data,
...rest
});
}, "Inspector");
// src/actions/components/ActionLogger/index.tsx
import { styled as styled32, withTheme } from "storybook/theming";
// src/actions/components/ActionLogger/style.tsx
import { styled as styled31 } from "storybook/theming";
var Action = styled31.div({
display: "flex",
padding: 0,
borderLeft: "5px solid transparent",
borderBottom: "1px solid transparent",
transition: "all 0.1s",
alignItems: "flex-start",
whiteSpace: "pre"
});
var Counter = styled31.div(({ theme: theme3 }) => ({
backgroundColor: curriedOpacify$1(0.5, theme3.appBorderColor),
color: theme3.color.inverseText,
fontSize: theme3.typography.size.s1,
fontWeight: theme3.typography.weight.bold,
lineHeight: 1,
padding: "1px 5px",
borderRadius: 20,
margin: "2px 0px"
}));
var InspectorContainer = styled31.div({
flex: 1,
padding: "0 0 0 5px"
});
// src/actions/components/ActionLogger/index.tsx
var UnstyledWrapped = forwardRef(
({ children, className }, ref) => React44.createElement(ScrollArea, { ref, horizontal: true, vertical: true, className }, children)
);
UnstyledWrapped.displayName = "UnstyledWrapped";
var Wrapper10 = styled32(UnstyledWrapped)({
margin: 0,
padding: "10px 5px 20px"
});
var ThemedInspector = withTheme(({ theme: theme3, ...props }) => React44.createElement(Inspector, { theme: theme3.addonActionsTheme || "chromeLight", table: false, ...props }));
var ActionLogger = /* @__PURE__ */ __name(({ actions, onClear }) => {
const wrapperRef = useRef6(null);
const wrapper = wrapperRef.current;
const wasAtBottom = wrapper && wrapper.scrollHeight - wrapper.scrollTop === wrapper.clientHeight;
useEffect12(() => {
if (wasAtBottom) {
wrapperRef.current.scrollTop = wrapperRef.current.scrollHeight;
}
}, [wasAtBottom, actions.length]);
return React44.createElement(Fragment, null, React44.createElement(Wrapper10, { ref: wrapperRef }, actions.map((action) => React44.createElement(Action, { key: action.id }, action.count > 1 && React44.createElement(Counter, null, action.count), React44.createElement(InspectorContainer, null, React44.createElement(
ThemedInspector,
{
sortObjectKeys: true,
showNonenumerable: false,
name: action.data.name,
data: action.data.args ?? action.data
}
))))), React44.createElement(ActionBar2, { actionItems: [{ title: "Clear", onClick: onClear }] }));
}, "ActionLogger");
// src/actions/containers/ActionLogger/index.tsx
var safeDeepEqual = /* @__PURE__ */ __name((a2, b2) => {
try {
return dequal(a2, b2);
} catch (e2) {
return false;
}
}, "safeDeepEqual");
var _ActionLogger = class _ActionLogger extends Component4 {
constructor(props) {
super(props);
this.handleStoryChange = /* @__PURE__ */ __name(() => {
const { actions } = this.state;
if (actions.length > 0 && actions[0].options.clearOnStoryChange) {
this.clearActions();
}
}, "handleStoryChange");
this.addAction = /* @__PURE__ */ __name((action) => {
this.setState((prevState) => {
const actions = [...prevState.actions];
const previous = actions.length && actions[actions.length - 1];
if (previous && safeDeepEqual(previous.data, action.data)) {
previous.count++;
} else {
action.count = 1;
actions.push(action);
}
return { actions: actions.slice(0, action.options.limit) };
});
}, "addAction");
this.clearActions = /* @__PURE__ */ __name(() => {
const { api } = this.props;
api.emit(CLEAR_ID);
this.setState({ actions: [] });
}, "clearActions");
this.mounted = false;
this.state = { actions: [] };
}
componentDidMount() {
this.mounted = true;
const { api } = this.props;
api.on(EVENT_ID, this.addAction);
api.on(STORY_CHANGED2, this.handleStoryChange);
}
componentWillUnmount() {
this.mounted = false;
const { api } = this.props;
api.off(STORY_CHANGED2, this.handleStoryChange);
api.off(EVENT_ID, this.addAction);
}
render() {
const { actions = [] } = this.state;
const { active } = this.props;
const props = {
actions,
onClear: this.clearActions
};
return active ? React45.createElement(ActionLogger, { ...props }) : null;
}
};
__name(_ActionLogger, "ActionLogger");
var ActionLogger2 = _ActionLogger;
// src/actions/manager.tsx
var manager_default2 = addons2.register(ADDON_ID, (api) => {
if (globalThis?.FEATURES?.actions) {
addons2.add(PANEL_ID, {
title: Title3,
type: types2.PANEL,
render: /* @__PURE__ */ __name(({ active }) => React46.createElement(ActionLogger2, { api, active: !!active }), "render"),
paramKey: PARAM_KEY
});
}
});
// src/component-testing/manager.tsx
import React69 from "react";
import { AddonPanel as AddonPanel2 } from "storybook/internal/components";
import { Consumer, addons as addons3, types as types3 } from "storybook/manager-api";
// src/component-testing/components/Panel.tsx
import React67, { Fragment as Fragment3, memo as memo4, useEffect as useEffect18, useMemo as useMemo5, useRef as useRef7, useState as useState23 } from "react";
import {
FORCE_REMOUNT,
PLAY_FUNCTION_THREW_EXCEPTION,
STORY_RENDER_PHASE_CHANGED,
STORY_THREW_EXCEPTION,
UNHANDLED_ERRORS_WHILE_PLAYING
} from "storybook/internal/core-events";
import { global as global2 } from "@storybook/global";
import {
experimental_useStatusStore,
useAddonState as useAddonState2,
useChannel as useChannel2,
useParameter as useParameter2,
useStorybookApi as useStorybookApi6,
useStorybookState as useStorybookState2
} from "storybook/manager-api";
// src/component-testing/constants.ts
var ADDON_ID7 = "storybook/interactions";
var PANEL_ID2 = `${ADDON_ID7}/panel`;
var DOCUMENTATION_LINK = "writing-tests/integrations/vitest-addon";
var DOCUMENTATION_DISCREPANCY_LINK = `${DOCUMENTATION_LINK}#what-happens-when-there-are-different-test-results-in-multiple-environments`;
var DOCUMENTATION_PLAY_FUNCTION_LINK = "writing-stories/play-function#writing-stories-with-the-play-function";
var INTERNAL_RENDER_CALL_ID = "internal_render_call";
// ../addons/a11y/src/constants.ts
var ADDON_ID8 = "storybook/a11y";
var PANEL_ID3 = `${ADDON_ID8}/panel`;
var UI_STATE_ID = `${ADDON_ID8}/ui`;
var RESULT = `${ADDON_ID8}/result`;
var REQUEST = `${ADDON_ID8}/request`;
var RUNNING = `${ADDON_ID8}/running`;
var ERROR2 = `${ADDON_ID8}/error`;
var MANUAL = `${ADDON_ID8}/manual`;
var SELECT = `${ADDON_ID8}/select`;
var DOCUMENTATION_LINK2 = "writing-tests/accessibility-testing";
var DOCUMENTATION_DISCREPANCY_LINK2 = `${DOCUMENTATION_LINK2}#why-are-my-tests-failing-in-different-environments`;
// ../addons/vitest/src/constants.ts
var ADDON_ID9 = "storybook/test";
var TEST_PROVIDER_ID = `${ADDON_ID9}/test-provider`;
var STORYBOOK_ADDON_TEST_CHANNEL = "STORYBOOK_ADDON_TEST_CHANNEL";
var DOCUMENTATION_LINK3 = "writing-tests/integrations/vitest-addon";
var DOCUMENTATION_FATAL_ERROR_LINK = `${DOCUMENTATION_LINK3}#what-happens-if-vitest-itself-has-an-error`;
var storeOptions = {
id: ADDON_ID9,
initialState: {
config: {
coverage: false,
a11y: false
},
watching: false,
cancelling: false,
fatalError: void 0,
indexUrl: void 0,
previewAnnotations: [],
currentRun: {
triggeredBy: void 0,
config: {
coverage: false,
a11y: false
},
componentTestCount: {
success: 0,
error: 0
},
a11yCount: {
success: 0,
warning: 0,
error: 0
},
storyIds: void 0,
totalTestCount: void 0,
startedAt: void 0,
finishedAt: void 0,
unhandledErrors: [],
coverageSummary: void 0
}
}
};
var STORE_CHANNEL_EVENT_NAME = `UNIVERSAL_STORE:${storeOptions.id}`;
var STATUS_TYPE_ID_COMPONENT_TEST = "storybook/component-test";
// src/component-testing/components/InteractionsPanel.tsx
import * as React66 from "react";
import { styled as styled41 } from "storybook/theming";
// src/component-testing/utils.ts
var import_ansi_to_html = __toESM(require_ansi_to_html(), 1);
import { useTheme as useTheme3 } from "storybook/theming";
// ../node_modules/ansi-regex/index.js
function ansiRegex({ onlyFirst = false } = {}) {
const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`;
const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
const pattern = `${osc}|${csi}`;
return new RegExp(pattern, onlyFirst ? void 0 : "g");
}
__name(ansiRegex, "ansiRegex");
// ../node_modules/strip-ansi/index.js
var regex = ansiRegex();
function stripAnsi(string) {
if (typeof string !== "string") {
throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
}
return string.replace(regex, "");
}
__name(stripAnsi, "stripAnsi");
// src/component-testing/utils.ts
function isTestAssertionError(error) {
return isChaiError(error) || isJestError(error);
}
__name(isTestAssertionError, "isTestAssertionError");
function isChaiError(error) {
return error && typeof error === "object" && "name" in error && typeof error.name === "string" && error.name === "AssertionError";
}
__name(isChaiError, "isChaiError");
function isJestError(error) {
return error && typeof error === "object" && "message" in error && typeof error.message === "string" && stripAnsi(error.message).startsWith("expect(");
}
__name(isJestError, "isJestError");
function createAnsiToHtmlFilter(theme3) {
return new import_ansi_to_html.default({
escapeXML: true,
fg: theme3.color.defaultText,
bg: theme3.background.content
});
}
__name(createAnsiToHtmlFilter, "createAnsiToHtmlFilter");
function useAnsiToHtmlFilter() {
const theme3 = useTheme3();
return createAnsiToHtmlFilter(theme3);
}
__name(useAnsiToHtmlFilter, "useAnsiToHtmlFilter");
// src/component-testing/components/DetachedDebuggerMessage.tsx
import React47 from "react";
import { Link as Link4 } from "storybook/internal/components";
import { styled as styled33 } from "storybook/theming";
var Wrapper11 = styled33.div(({ theme: { color: color2, typography: typography4, background } }) => ({
textAlign: "start",
padding: "11px 15px",
fontSize: `${typography4.size.s2 - 1}px`,
fontWeight: typography4.weight.regular,
lineHeight: "1rem",
background: background.app,
borderBottom: `1px solid ${color2.border}`,
color: color2.defaultText,
backgroundClip: "padding-box",
position: "relative"
}));
var DetachedDebuggerMessage = /* @__PURE__ */ __name(({ storyUrl }) => {
return React47.createElement(Wrapper11, null, "Debugger controls are not available on composed Storybooks.", " ", React47.createElement(
Link4,
{
href: `${storyUrl}&addonPanel=${PANEL_ID2}`,
target: "_blank",
rel: "noopener noreferrer",
withArrow: true
},
"Open in external Storybook"
));
}, "DetachedDebuggerMessage");
// src/component-testing/components/EmptyState.tsx
import React48, { useEffect as useEffect13, useState as useState16 } from "react";
import { EmptyTabContent as EmptyTabContent2, Link as Link5 } from "storybook/internal/components";
import { DocumentIcon as DocumentIcon3 } from "@storybook/icons";
import { useStorybookApi as useStorybookApi4 } from "storybook/manager-api";
import { styled as styled34 } from "storybook/theming";
var Links2 = styled34.div(({ theme: theme3 }) => ({
display: "flex",
fontSize: theme3.typography.size.s2 - 1,
gap: 25
}));
var Empty2 = /* @__PURE__ */ __name(() => {
const [isLoading, setIsLoading] = useState16(true);
const api = useStorybookApi4();
const docsUrl = api.getDocsUrl({
subpath: DOCUMENTATION_PLAY_FUNCTION_LINK,
versioned: true,
renderer: true
});
useEffect13(() => {
const load = setTimeout(() => {
setIsLoading(false);
}, 100);
return () => clearTimeout(load);
}, []);
if (isLoading) {
return null;
}
return React48.createElement("div", null, React48.createElement(
EmptyTabContent2,
{
title: "Interactions",
description: React48.createElement(React48.Fragment, null, "Interactions allow you to verify the functional aspects of UIs. Write a play function for your story and you'll see it run here."),
footer: React48.createElement(Links2, null, React48.createElement(Link5, { href: docsUrl, target: "_blank", withArrow: true }, React48.createElement(DocumentIcon3, null), " Read docs"))
}
));
}, "Empty");
// src/component-testing/components/Interaction.tsx
import * as React61 from "react";
import { IconButton as IconButton5, TooltipNote as TooltipNote2, WithTooltip as WithTooltip2 } from "storybook/internal/components";
import { ChevronDownIcon as ChevronDownIcon3, ChevronUpIcon as ChevronUpIcon2 } from "@storybook/icons";
import { styled as styled37, typography as typography2 } from "storybook/theming";
// src/component-testing/components/MatcherResult.tsx
import React59 from "react";
import { styled as styled35, typography } from "storybook/theming";
// src/component-testing/components/MethodCall.tsx
import React58, { Fragment as Fragment2 } from "react";
import { logger as logger4 } from "storybook/internal/client-logger";
// ../node_modules/@devtools-ds/object-inspector/dist/esm/ObjectInspector.js
import React57, { useEffect as useEffect17, useState as useState20 } from "react";
// ../node_modules/clsx/dist/clsx.m.js
function toVal(mix) {
var k2, y2, str = "";
if (mix) {
if (typeof mix === "object") {
if (Array.isArray(mix)) {
for (k2 = 0; k2 < mix.length; k2++) {
if (mix[k2] && (y2 = toVal(mix[k2]))) {
str && (str += " ");
str += y2;
}
}
} else {
for (k2 in mix) {
if (mix[k2] && (y2 = toVal(k2))) {
str && (str += " ");
str += y2;
}
}
}
} else if (typeof mix !== "boolean" && !mix.call) {
str && (str += " ");
str += mix;
}
}
return str;
}
__name(toVal, "toVal");
function clsx_m_default() {
var i2 = 0, x2, str = "";
while (i2 < arguments.length) {
if (x2 = toVal(arguments[i2++])) {
str && (str += " ");
str += x2;
}
}
return str;
}
__name(clsx_m_default, "default");
// ../node_modules/@devtools-ds/object-parser/dist/esm/index.js
var isArray = /* @__PURE__ */ __name((val) => {
return Array.isArray(val) || // Detect https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
ArrayBuffer.isView(val) && !(val instanceof DataView);
}, "isArray");
var isObject = /* @__PURE__ */ __name((val) => {
return val !== null && typeof val === "object" && !isArray(val) && !(val instanceof Date) && !(val instanceof RegExp) && !(val instanceof Error) && !(val instanceof WeakMap) && !(val instanceof WeakSet);
}, "isObject");
var isKnownObject = /* @__PURE__ */ __name((val) => {
return isObject(val) || isArray(val) || typeof val === "function" || val instanceof Promise;
}, "isKnownObject");
var getPromiseState = /* @__PURE__ */ __name((promise) => {
const unique = /unique/;
return Promise.race([promise, unique]).then((result) => result === unique ? ["pending"] : ["fulfilled", result], (e2) => ["rejected", e2]);
}, "getPromiseState");
var buildAST = /* @__PURE__ */ __name(async (key, value2, depth, sortKeys, isPrototype, showPrototype) => {
const astNode = {
key,
depth,
value: value2,
type: "value",
parent: void 0
};
if (value2 && isKnownObject(value2) && depth < 100) {
const children = [];
let t = "object";
if (isArray(value2)) {
for (let i2 = 0; i2 < value2.length; i2++) {
children.push(async () => {
const child = await buildAST(i2.toString(), value2[i2], depth + 1, sortKeys);
child.parent = astNode;
return child;
});
}
t = "array";
} else {
const keys = Object.getOwnPropertyNames(value2);
if (sortKeys) keys.sort();
for (let i2 = 0; i2 < keys.length; i2++) {
let safeValue;
try {
safeValue = value2[keys[i2]];
} catch (e2) {
}
children.push(async () => {
const child = await buildAST(keys[i2], safeValue, depth + 1, sortKeys);
child.parent = astNode;
return child;
});
}
if (typeof value2 === "function") {
t = "function";
}
if (value2 instanceof Promise) {
const [status, result] = await getPromiseState(value2);
children.push(async () => {
const child = await buildAST("<state>", status, depth + 1, sortKeys);
child.parent = astNode;
return child;
});
if (status !== "pending") {
children.push(async () => {
const child = await buildAST("<value>", result, depth + 1, sortKeys);
child.parent = astNode;
return child;
});
}
t = "promise";
}
if (value2 instanceof Map) {
const entries = Array.from(value2.entries());
const parsedEntries = entries.map((entry) => {
const [entryKey, entryValue] = entry;
return {
"<key>": entryKey,
"<value>": entryValue
};
});
children.push(async () => {
const child = await buildAST("<entries>", parsedEntries, depth + 1, sortKeys);
child.parent = astNode;
return child;
});
children.push(async () => {
const child = await buildAST("size", value2.size, depth + 1, sortKeys);
child.parent = astNode;
return child;
});
t = "map";
}
if (value2 instanceof Set) {
const entries = Array.from(value2.entries());
const parsedEntries = entries.map((entry) => {
return entry[1];
});
children.push(async () => {
const child = await buildAST("<entries>", parsedEntries, depth + 1, sortKeys);
child.parent = astNode;
return child;
});
children.push(async () => {
const child = await buildAST("size", value2.size, depth + 1, sortKeys);
child.parent = astNode;
return child;
});
t = "set";
}
}
if (value2 !== Object.prototype && showPrototype) {
children.push(async () => {
const child = await buildAST("<prototype>", Object.getPrototypeOf(value2), depth + 1, sortKeys, true);
child.parent = astNode;
return child;
});
}
astNode.type = t;
astNode.children = children;
astNode.isPrototype = isPrototype;
}
return astNode;
}, "buildAST");
var parse4 = /* @__PURE__ */ __name((data, sortKeys, includePrototypes) => {
const keys = sortKeys === false ? sortKeys : true;
const prototypes = includePrototypes === false ? includePrototypes : true;
return buildAST("root", data, 0, keys, void 0, prototypes);
}, "parse");
// ../node_modules/@babel/runtime/helpers/esm/objectSpread2.js
function ownKeys(e2, r2) {
var t = Object.keys(e2);
if (Object.getOwnPropertySymbols) {
var o2 = Object.getOwnPropertySymbols(e2);
r2 && (o2 = o2.filter(function(r3) {
return Object.getOwnPropertyDescriptor(e2, r3).enumerable;
})), t.push.apply(t, o2);
}
return t;
}
__name(ownKeys, "ownKeys");
function _objectSpread2(e2) {
for (var r2 = 1; r2 < arguments.length; r2++) {
var t = null != arguments[r2] ? arguments[r2] : {};
r2 % 2 ? ownKeys(Object(t), true).forEach(function(r3) {
_defineProperty(e2, r3, t[r3]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r3) {
Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t, r3));
});
}
return e2;
}
__name(_objectSpread2, "_objectSpread2");
// ../node_modules/@devtools-ds/themes/dist/esm/utils.js
import React49 from "react";
var _excluded = ["children"];
var ThemeContext2 = React49.createContext({
theme: "chrome",
colorScheme: "light"
});
var ThemeProvider2 = /* @__PURE__ */ __name((_ref) => {
let {
children
} = _ref, value2 = _objectWithoutProperties(_ref, _excluded);
const wrappedTheme = React49.useContext(ThemeContext2);
return React49.createElement(ThemeContext2.Provider, {
value: _objectSpread2(_objectSpread2({}, wrappedTheme), value2)
}, children);
}, "ThemeProvider");
var useTheme4 = /* @__PURE__ */ __name((props, styles = {}) => {
const themeContext = React49.useContext(ThemeContext2);
const currentTheme = props.theme || themeContext.theme || "chrome";
const currentColorScheme = props.colorScheme || themeContext.colorScheme || "light";
const themeClass = clsx_m_default(styles[currentTheme], styles[currentColorScheme]);
return {
currentColorScheme,
currentTheme,
themeClass
};
}, "useTheme");
// ../node_modules/@devtools-ds/themes/dist/esm/AutoThemeProvider.js
import React50 from "react";
// ../node_modules/@devtools-ds/object-inspector/dist/esm/ObjectInspectorItem.js
import React56, { useEffect as useEffect16, useState as useState19 } from "react";
// ../node_modules/@devtools-ds/tree/dist/esm/index.js
import React53, { useState as useState17, useEffect as useEffect14 } from "react";
// ../node_modules/@devtools-ds/tree/dist/esm/TreeContext.js
import React51 from "react";
var TreeContext = React51.createContext({
isChild: false,
depth: 0,
hasHover: true
});
var TreeContext_default = TreeContext;
// ../node_modules/@devtools-ds/tree/dist/esm/Tree.css.js
var Tree_css_default = { "tree": "Tree-tree-fbbbe38", "item": "Tree-item-353d6f3", "group": "Tree-group-d3c3d8a", "label": "Tree-label-d819155", "focusWhite": "Tree-focusWhite-f1e00c2", "arrow": "Tree-arrow-03ab2e7", "hover": "Tree-hover-3cc4e5d", "open": "Tree-open-3f1a336", "dark": "Tree-dark-1b4aa00", "chrome": "Tree-chrome-bcbcac6", "light": "Tree-light-09174ee" };
// ../node_modules/@devtools-ds/tree/dist/esm/index.js
var _excluded2 = ["theme", "hover", "colorScheme", "children", "label", "className", "onUpdate", "onSelect", "open"];
var Tree = /* @__PURE__ */ __name((props) => {
const {
theme: theme3,
hover,
colorScheme,
children,
label,
className,
onUpdate,
onSelect,
open
} = props, html = _objectWithoutProperties(props, _excluded2);
const {
themeClass,
currentTheme
} = useTheme4({
theme: theme3,
colorScheme
}, Tree_css_default);
const [isOpen, setOpen] = useState17(open);
useEffect14(() => {
setOpen(open);
}, [open]);
const updateState = /* @__PURE__ */ __name((value2) => {
setOpen(value2);
if (onUpdate) onUpdate(value2);
}, "updateState");
const hasChildren = React53.Children.count(children) > 0;
const updateFocus = /* @__PURE__ */ __name((newNode, previousNode) => {
if (newNode.isSameNode(previousNode || null)) return;
const focusableNode = newNode.querySelector('[tabindex="-1"]');
focusableNode === null || focusableNode === void 0 ? void 0 : focusableNode.focus();
newNode.setAttribute("aria-selected", "true");
previousNode === null || previousNode === void 0 ? void 0 : previousNode.removeAttribute("aria-selected");
}, "updateFocus");
const getParent = /* @__PURE__ */ __name((node, role) => {
let parent = node;
while (parent && parent.parentElement) {
if (parent.getAttribute("role") === role) {
return parent;
}
parent = parent.parentElement;
}
return null;
}, "getParent");
const getListElements = /* @__PURE__ */ __name((node) => {
const tree = getParent(node, "tree");
if (!tree) return [];
return Array.from(tree.querySelectorAll("li"));
}, "getListElements");
const moveBack = /* @__PURE__ */ __name((node) => {
const group = getParent(node, "group");
const toggle = group === null || group === void 0 ? void 0 : group.previousElementSibling;
if (toggle && toggle.getAttribute("tabindex") === "-1") {
const toggleParent = toggle.parentElement;
const nodeParent = node.parentElement;
updateFocus(toggleParent, nodeParent);
}
}, "moveBack");
const moveHome = /* @__PURE__ */ __name((node, direction) => {
const elements = getListElements(node);
elements.forEach((element) => {
element.removeAttribute("aria-selected");
});
if (direction === "start" && elements[0]) {
updateFocus(elements[0]);
}
if (direction === "end" && elements[elements.length - 1]) {
updateFocus(elements[elements.length - 1]);
}
}, "moveHome");
const moveFocusAdjacent = /* @__PURE__ */ __name((node, direction) => {
const elements = getListElements(node) || [];
for (let i2 = 0; i2 < elements.length; i2++) {
const currentNode = elements[i2];
if (currentNode.getAttribute("aria-selected") === "true") {
if (direction === "up" && elements[i2 - 1]) {
updateFocus(elements[i2 - 1], currentNode);
} else if (direction === "down" && elements[i2 + 1]) {
updateFocus(elements[i2 + 1], currentNode);
}
return;
}
}
updateFocus(elements[0]);
}, "moveFocusAdjacent");
const handleKeypress = /* @__PURE__ */ __name((event, isChild2) => {
const node = event.target;
if (event.key === "Enter" || event.key === " ") {
updateState(!isOpen);
}
if (event.key === "ArrowRight" && isOpen && !isChild2) {
moveFocusAdjacent(node, "down");
} else if (event.key === "ArrowRight") {
updateState(true);
}
if (event.key === "ArrowLeft" && (!isOpen || isChild2)) {
moveBack(node);
} else if (event.key === "ArrowLeft") {
updateState(false);
}
if (event.key === "ArrowDown") {
moveFocusAdjacent(node, "down");
}
if (event.key === "ArrowUp") {
moveFocusAdjacent(node, "up");
}
if (event.key === "Home") {
moveHome(node, "start");
}
if (event.key === "End") {
moveHome(node, "end");
}
}, "handleKeypress");
const handleClick = /* @__PURE__ */ __name((event, isChild2) => {
const node = event.target;
const parent = getParent(node, "treeitem");
const elements = getListElements(node) || [];
let found = false;
for (let i2 = 0; i2 < elements.length; i2++) {
const currentNode = elements[i2];
if (currentNode.getAttribute("aria-selected") === "true") {
if (parent) {
found = true;
updateFocus(parent, currentNode);
}
break;
}
}
if (!found && parent) {
updateFocus(parent);
}
if (!isChild2) {
updateState(!isOpen);
}
}, "handleClick");
const handleBlur = /* @__PURE__ */ __name((event) => {
const node = event.currentTarget;
if (!node.contains(document.activeElement) && node.getAttribute("role") === "tree") {
node.setAttribute("tabindex", "0");
}
}, "handleBlur");
const handleFocus = /* @__PURE__ */ __name((event) => {
const node = event.target;
if (node.getAttribute("role") === "tree") {
const selected = node.querySelector('[aria-selected="true"]');
if (selected) {
updateFocus(selected);
} else {
moveFocusAdjacent(node, "down");
}
node.setAttribute("tabindex", "-1");
}
}, "handleFocus");
const handleButtonFocus = /* @__PURE__ */ __name(() => {
onSelect === null || onSelect === void 0 ? void 0 : onSelect();
}, "handleButtonFocus");
const getPaddingStyles = /* @__PURE__ */ __name((depth2) => {
const space = depth2 * 0.9 + 0.3;
return {
paddingLeft: `${space}em`,
width: `calc(100% - ${space}em)`
};
}, "getPaddingStyles");
const {
isChild,
depth,
hasHover
} = React53.useContext(TreeContext_default);
const showHover = hasHover ? hover : false;
if (!isChild) {
return React53.createElement("ul", _extends({
role: "tree",
tabIndex: 0,
className: clsx_m_default(Tree_css_default.tree, Tree_css_default.group, themeClass, className),
onFocus: handleFocus,
onBlur: handleBlur
}, html), React53.createElement(TreeContext_default.Provider, {
value: {
isChild: true,
depth: 0,
hasHover: showHover
}
}, React53.createElement(Tree, props)));
}
if (!hasChildren) {
return React53.createElement("li", _extends({
role: "treeitem",
className: Tree_css_default.item
}, html), React53.createElement("div", {
role: "button",
className: clsx_m_default(Tree_css_default.label, {
[Tree_css_default.hover]: showHover,
[Tree_css_default.focusWhite]: currentTheme === "firefox"
}),
tabIndex: -1,
style: getPaddingStyles(depth),
onKeyDown: /* @__PURE__ */ __name((e2) => {
handleKeypress(e2, isChild);
}, "onKeyDown"),
onClick: /* @__PURE__ */ __name((e2) => handleClick(e2, true), "onClick"),
onFocus: handleButtonFocus
}, React53.createElement("span", null, label)));
}
const arrowClass = clsx_m_default(Tree_css_default.arrow, {
[Tree_css_default.open]: isOpen
});
return React53.createElement("li", {
role: "treeitem",
"aria-expanded": isOpen,
className: Tree_css_default.item
}, React53.createElement("div", {
role: "button",
tabIndex: -1,
className: clsx_m_default(Tree_css_default.label, {
[Tree_css_default.hover]: showHover,
[Tree_css_default.focusWhite]: currentTheme === "firefox"
}),
style: getPaddingStyles(depth),
onClick: /* @__PURE__ */ __name((e2) => handleClick(e2), "onClick"),
onKeyDown: /* @__PURE__ */ __name((e2) => handleKeypress(e2), "onKeyDown"),
onFocus: handleButtonFocus
}, React53.createElement("span", null, React53.createElement("span", {
"aria-hidden": true,
className: arrowClass
}), React53.createElement("span", null, label))), React53.createElement("ul", _extends({
role: "group",
className: clsx_m_default(className, Tree_css_default.group)
}, html), isOpen && React53.Children.map(children, (child) => {
return React53.createElement(TreeContext_default.Provider, {
value: {
isChild: true,
depth: depth + 1,
hasHover: showHover
}
}, child);
})));
}, "Tree");
Tree.defaultProps = {
open: false,
hover: true
};
// ../node_modules/@devtools-ds/object-inspector/dist/esm/ObjectValue.js
import React54, { useState as useState18, useEffect as useEffect15 } from "react";
// ../node_modules/@devtools-ds/object-inspector/dist/esm/ObjectInspector.css.js
var ObjectInspector_css_default = { "object-inspector": "ObjectInspector-object-inspector-0c33e82", "objectInspector": "ObjectInspector-object-inspector-0c33e82", "object-label": "ObjectInspector-object-label-b81482b", "objectLabel": "ObjectInspector-object-label-b81482b", "text": "ObjectInspector-text-25f57f3", "key": "ObjectInspector-key-4f712bb", "value": "ObjectInspector-value-f7ec2e5", "string": "ObjectInspector-string-c496000", "regex": "ObjectInspector-regex-59d45a3", "error": "ObjectInspector-error-b818698", "boolean": "ObjectInspector-boolean-2dd1642", "number": "ObjectInspector-number-a6daabb", "undefined": "ObjectInspector-undefined-3a68263", "null": "ObjectInspector-null-74acb50", "function": "ObjectInspector-function-07bbdcd", "function-decorator": "ObjectInspector-function-decorator-3d22c24", "functionDecorator": "ObjectInspector-function-decorator-3d22c24", "prototype": "ObjectInspector-prototype-f2449ee", "dark": "ObjectInspector-dark-0c96c97", "chrome": "ObjectInspector-chrome-2f3ca98", "light": "ObjectInspector-light-78bef54" };
// ../node_modules/@devtools-ds/object-inspector/dist/esm/ObjectValue.js
var _excluded3 = ["ast", "theme", "showKey", "colorScheme", "className"];
var buildValue = /* @__PURE__ */ __name((key, value2, valueClass, showKey, depth) => {
const computedKey = key.includes("-") ? `"${key}"` : key;
const isRoot = depth <= 0;
return React54.createElement("span", {
className: ObjectInspector_css_default.text
}, !isRoot && showKey && React54.createElement(React54.Fragment, null, React54.createElement("span", {
className: ObjectInspector_css_default.key
}, computedKey), React54.createElement("span", null, ":\xA0")), React54.createElement("span", {
className: valueClass
}, value2));
}, "buildValue");
var ObjectValue2 = /* @__PURE__ */ __name((props) => {
const {
ast,
theme: theme3,
showKey,
colorScheme,
className
} = props, html = _objectWithoutProperties(props, _excluded3);
const {
themeClass
} = useTheme4({
theme: theme3,
colorScheme
}, ObjectInspector_css_default);
const [asyncValue, setAsyncValue] = useState18(React54.createElement("span", null));
let value2 = React54.createElement("span", null);
useEffect15(() => {
if (ast.value instanceof Promise) {
const waitForPromiseResult = /* @__PURE__ */ __name(async (promise) => {
setAsyncValue(buildValue(ast.key, `Promise { "${await getPromiseState(promise)}" }`, ObjectInspector_css_default.key, showKey, ast.depth));
}, "waitForPromiseResult");
waitForPromiseResult(ast.value);
}
}, [ast, showKey]);
if (typeof ast.value === "number" || typeof ast.value === "bigint") {
value2 = buildValue(ast.key, String(ast.value), ObjectInspector_css_default.number, showKey, ast.depth);
} else if (typeof ast.value === "boolean") {
value2 = buildValue(ast.key, String(ast.value), ObjectInspector_css_default.boolean, showKey, ast.depth);
} else if (typeof ast.value === "string") {
value2 = buildValue(ast.key, `"${ast.value}"`, ObjectInspector_css_default.string, showKey, ast.depth);
} else if (typeof ast.value === "undefined") {
value2 = buildValue(ast.key, "undefined", ObjectInspector_css_default.undefined, showKey, ast.depth);
} else if (typeof ast.value === "symbol") {
value2 = buildValue(ast.key, ast.value.toString(), ObjectInspector_css_default.string, showKey, ast.depth);
} else if (typeof ast.value === "function") {
value2 = buildValue(ast.key, `${ast.value.name}()`, ObjectInspector_css_default.key, showKey, ast.depth);
} else if (typeof ast.value === "object") {
if (ast.value === null) {
value2 = buildValue(ast.key, "null", ObjectInspector_css_default.null, showKey, ast.depth);
} else if (Array.isArray(ast.value)) {
value2 = buildValue(ast.key, `Array(${ast.value.length})`, ObjectInspector_css_default.key, showKey, ast.depth);
} else if (ast.value instanceof Date) {
value2 = buildValue(ast.key, `Date ${ast.value.toString()}`, ObjectInspector_css_default.value, showKey, ast.depth);
} else if (ast.value instanceof RegExp) {
value2 = buildValue(ast.key, ast.value.toString(), ObjectInspector_css_default.regex, showKey, ast.depth);
} else if (ast.value instanceof Error) {
value2 = buildValue(ast.key, ast.value.toString(), ObjectInspector_css_default.error, showKey, ast.depth);
} else if (isObject(ast.value)) {
value2 = buildValue(ast.key, "{\u2026}", ObjectInspector_css_default.key, showKey, ast.depth);
} else {
value2 = buildValue(ast.key, ast.value.constructor.name, ObjectInspector_css_default.key, showKey, ast.depth);
}
}
return React54.createElement("span", _extends({
className: clsx_m_default(themeClass, className)
}, html), asyncValue, value2);
}, "ObjectValue");
ObjectValue2.defaultProps = {
showKey: true
};
var ObjectValue_default = ObjectValue2;
// ../node_modules/@devtools-ds/object-inspector/dist/esm/ObjectLabel.js
import React55 from "react";
var _excluded4 = ["ast", "theme", "previewMax", "open", "colorScheme", "className"];
var buildPreview = /* @__PURE__ */ __name((children, previewMax, showKey) => {
const previews = [];
for (let i2 = 0; i2 < children.length; i2++) {
const child = children[i2];
if (!child.isPrototype) {
previews.push(React55.createElement(ObjectValue_default, {
key: child.key,
ast: child,
showKey
}));
if (i2 < children.length - 1) {
previews.push(", ");
} else {
previews.push(" ");
}
}
if (child.isPrototype && i2 === children.length - 1) {
previews.pop();
previews.push(" ");
}
if (i2 === previewMax - 1 && children.length > previewMax) {
previews.push("\u2026 ");
break;
}
}
return previews;
}, "buildPreview");
var getArrayLabel = /* @__PURE__ */ __name((ast, open, previewMax, theme3) => {
const l2 = ast.value.length;
if (open) {
return React55.createElement("span", null, "Array(", l2, ")");
}
return React55.createElement(React55.Fragment, null, React55.createElement("span", null, `${theme3 === "firefox" ? "Array" : ""}(${l2}) [ `), buildPreview(ast.children, previewMax, false), React55.createElement("span", null, "]"));
}, "getArrayLabel");
var getObjectLabel = /* @__PURE__ */ __name((ast, open, previewMax, theme3) => {
if (ast.isPrototype) {
return React55.createElement("span", null, `Object ${theme3 === "firefox" ? "{ \u2026 }" : ""}`);
}
if (open) {
return React55.createElement("span", null, "{\u2026}");
}
return React55.createElement(React55.Fragment, null, React55.createElement("span", null, `${theme3 === "firefox" ? "Object " : ""}{ `), buildPreview(ast.children, previewMax, true), React55.createElement("span", null, "}"));
}, "getObjectLabel");
var getPromiseLabel = /* @__PURE__ */ __name((ast, open, previewMax) => {
if (open) {
return React55.createElement("span", null, `Promise { "${String(ast.children[0].value)}" }`);
}
return React55.createElement(React55.Fragment, null, React55.createElement("span", null, `Promise { `), buildPreview(ast.children, previewMax, true), React55.createElement("span", null, "}"));
}, "getPromiseLabel");
var getMapLabel = /* @__PURE__ */ __name((ast, open, previewMax, theme3) => {
const {
size
} = ast.value;
if (open) {
return React55.createElement("span", null, `Map(${size})`);
}
return React55.createElement(React55.Fragment, null, React55.createElement("span", null, `Map${theme3 === "chrome" ? `(${size})` : ""} { `), buildPreview(ast.children, previewMax, true), React55.createElement("span", null, "}"));
}, "getMapLabel");
var getSetLabel = /* @__PURE__ */ __name((ast, open, previewMax) => {
const {
size
} = ast.value;
if (open) {
return React55.createElement("span", null, "Set(", size, ")");
}
return React55.createElement(React55.Fragment, null, React55.createElement("span", null, `Set(${ast.value.size}) {`), buildPreview(ast.children, previewMax, true), React55.createElement("span", null, "}"));
}, "getSetLabel");
var ObjectLabel2 = /* @__PURE__ */ __name((props) => {
const {
ast,
theme: theme3,
previewMax,
open,
colorScheme,
className
} = props, html = _objectWithoutProperties(props, _excluded4);
const {
themeClass,
currentTheme
} = useTheme4({
theme: theme3,
colorScheme
}, ObjectInspector_css_default);
const isPrototype = ast.isPrototype || false;
const classes = clsx_m_default(ObjectInspector_css_default.objectLabel, themeClass, className, {
[ObjectInspector_css_default.prototype]: isPrototype
});
const isRoot = ast.depth <= 0;
const Key = /* @__PURE__ */ __name(() => {
return React55.createElement("span", {
className: isPrototype ? ObjectInspector_css_default.prototype : ObjectInspector_css_default.key
}, isRoot ? "" : `${ast.key}: `);
}, "Key");
if (ast.type === "array") {
return React55.createElement("span", _extends({
className: classes
}, html), React55.createElement(Key, null), getArrayLabel(ast, open, previewMax, currentTheme));
}
if (ast.type === "function") {
return React55.createElement("span", _extends({
className: classes
}, html), React55.createElement(Key, null), currentTheme === "chrome" && React55.createElement("span", {
className: ObjectInspector_css_default.functionDecorator
}, "\u0192 "), React55.createElement("span", {
className: clsx_m_default({
[ObjectInspector_css_default.function]: !isPrototype
})
}, `${ast.value.name}()`));
}
if (ast.type === "promise") {
return React55.createElement("span", _extends({
className: classes
}, html), React55.createElement(Key, null), getPromiseLabel(ast, open, previewMax));
}
if (ast.type === "map") {
return React55.createElement("span", _extends({
className: classes
}, html), React55.createElement(Key, null), getMapLabel(ast, open, previewMax, currentTheme));
}
if (ast.type === "set") {
return React55.createElement("span", _extends({
className: classes
}, html), React55.createElement(Key, null), getSetLabel(ast, open, previewMax));
}
return React55.createElement("span", _extends({
className: classes
}, html), React55.createElement(Key, null), getObjectLabel(ast, open, previewMax, currentTheme));
}, "ObjectLabel");
ObjectLabel2.defaultProps = {
previewMax: 8,
open: false
};
var ObjectLabel_default = ObjectLabel2;
// ../node_modules/@devtools-ds/object-inspector/dist/esm/ObjectInspectorItem.js
var ObjectInspectorItem = /* @__PURE__ */ __name((props) => {
const {
ast,
expandLevel,
depth
} = props;
const [resolved, setResolved] = useState19();
const [open, setOpen] = useState19(Boolean(depth < expandLevel));
useEffect16(() => {
const resolve = /* @__PURE__ */ __name(async () => {
if (ast.type !== "value") {
const promises = ast.children.map((f2) => f2());
const children = await Promise.all(promises);
const r2 = _objectSpread2(_objectSpread2({}, ast), {}, {
children
});
setResolved(r2);
}
}, "resolve");
resolve();
}, [ast]);
if (resolved) {
return React56.createElement(Tree, {
hover: false,
open,
label: React56.createElement(ObjectLabel_default, {
open,
ast: resolved
}),
onSelect: /* @__PURE__ */ __name(() => {
var _props$onSelect;
(_props$onSelect = props.onSelect) === null || _props$onSelect === void 0 ? void 0 : _props$onSelect.call(props, ast);
}, "onSelect"),
onUpdate: /* @__PURE__ */ __name((value2) => {
setOpen(value2);
}, "onUpdate")
}, resolved.children.map((child) => {
return React56.createElement(ObjectInspectorItem, {
key: child.key,
ast: child,
depth: depth + 1,
expandLevel,
onSelect: props.onSelect
});
}));
}
return React56.createElement(Tree, {
hover: false,
label: React56.createElement(ObjectValue_default, {
ast
}),
onSelect: /* @__PURE__ */ __name(() => {
var _props$onSelect2;
(_props$onSelect2 = props.onSelect) === null || _props$onSelect2 === void 0 ? void 0 : _props$onSelect2.call(props, ast);
}, "onSelect")
});
}, "ObjectInspectorItem");
ObjectInspectorItem.defaultProps = {
expandLevel: 0,
depth: 0
};
var ObjectInspectorItem_default = ObjectInspectorItem;
// ../node_modules/@devtools-ds/object-inspector/dist/esm/ObjectInspector.js
var _excluded5 = ["data", "expandLevel", "sortKeys", "includePrototypes", "className", "theme", "colorScheme", "onSelect"];
var ObjectInspector2 = /* @__PURE__ */ __name((props) => {
const {
data,
expandLevel,
sortKeys,
includePrototypes,
className,
theme: theme3,
colorScheme,
onSelect
} = props, html = _objectWithoutProperties(props, _excluded5);
const [ast, setAST] = useState20(void 0);
const {
themeClass,
currentTheme,
currentColorScheme
} = useTheme4({
theme: theme3,
colorScheme
}, ObjectInspector_css_default);
useEffect17(() => {
const runParser = /* @__PURE__ */ __name(async () => {
setAST(await parse4(data, sortKeys, includePrototypes));
}, "runParser");
runParser();
}, [data, sortKeys, includePrototypes]);
return React57.createElement("div", _extends({
className: clsx_m_default(ObjectInspector_css_default.objectInspector, className, themeClass)
}, html), ast && React57.createElement(ThemeProvider2, {
theme: currentTheme,
colorScheme: currentColorScheme
}, React57.createElement(ObjectInspectorItem_default, {
ast,
expandLevel,
onSelect
})));
}, "ObjectInspector");
ObjectInspector2.defaultProps = {
expandLevel: 0,
sortKeys: true,
includePrototypes: true
};
// src/component-testing/components/MethodCall.tsx
import { useTheme as useTheme5 } from "storybook/theming";
var colorsLight = {
base: "#444",
nullish: "#7D99AA",
string: "#16B242",
number: "#5D40D0",
boolean: "#f41840",
objectkey: "#698394",
instance: "#A15C20",
function: "#EA7509",
muted: "#7D99AA",
tag: {
name: "#6F2CAC",
suffix: "#1F99E5"
},
date: "#459D9C",
error: {
name: "#D43900",
message: "#444"
},
regex: {
source: "#A15C20",
flags: "#EA7509"
},
meta: "#EA7509",
method: "#0271B6"
};
var colorsDark = {
base: "#eee",
nullish: "#aaa",
string: "#5FE584",
number: "#6ba5ff",
boolean: "#ff4191",
objectkey: "#accfe6",
instance: "#E3B551",
function: "#E3B551",
muted: "#aaa",
tag: {
name: "#f57bff",
suffix: "#8EB5FF"
},
date: "#70D4D3",
error: {
name: "#f40",
message: "#eee"
},
regex: {
source: "#FAD483",
flags: "#E3B551"
},
meta: "#FAD483",
method: "#5EC1FF"
};
var useThemeColors = /* @__PURE__ */ __name(() => {
const { base } = useTheme5();
return base === "dark" ? colorsDark : colorsLight;
}, "useThemeColors");
var special = /[^A-Z0-9]/i;
var trimEnd = /[\s.,…]+$/gm;
var ellipsize = /* @__PURE__ */ __name((string, maxlength) => {
if (string.length <= maxlength) {
return string;
}
for (let i2 = maxlength - 1; i2 >= 0; i2 -= 1) {
if (special.test(string[i2]) && i2 > 10) {
return `${string.slice(0, i2).replace(trimEnd, "")}\u2026`;
}
}
return `${string.slice(0, maxlength).replace(trimEnd, "")}\u2026`;
}, "ellipsize");
var stringify = /* @__PURE__ */ __name((value2) => {
try {
return JSON.stringify(value2, null, 1);
} catch (e2) {
return String(value2);
}
}, "stringify");
var interleave = /* @__PURE__ */ __name((nodes, separator) => nodes.flatMap(
(node, index) => index === nodes.length - 1 ? [node] : [node, React58.cloneElement(separator, { key: `sep${index}` })]
), "interleave");
var Node2 = /* @__PURE__ */ __name(({
value: value2,
nested,
showObjectInspector,
callsById,
...props
}) => {
switch (true) {
case value2 === null:
return React58.createElement(NullNode, { ...props });
case value2 === void 0:
return React58.createElement(UndefinedNode, { ...props });
case Array.isArray(value2):
return React58.createElement(ArrayNode, { ...props, value: value2, callsById });
case typeof value2 === "string":
return React58.createElement(StringNode, { ...props, value: value2 });
case typeof value2 === "number":
return React58.createElement(NumberNode, { ...props, value: value2 });
case typeof value2 === "boolean":
return React58.createElement(BooleanNode, { ...props, value: value2 });
case Object.prototype.hasOwnProperty.call(value2, "__date__"):
return React58.createElement(DateNode, { ...props, ...value2.__date__ });
case Object.prototype.hasOwnProperty.call(value2, "__error__"):
return React58.createElement(ErrorNode, { ...props, ...value2.__error__ });
case Object.prototype.hasOwnProperty.call(value2, "__regexp__"):
return React58.createElement(RegExpNode, { ...props, ...value2.__regexp__ });
case Object.prototype.hasOwnProperty.call(value2, "__function__"):
return React58.createElement(FunctionNode, { ...props, ...value2.__function__ });
case Object.prototype.hasOwnProperty.call(value2, "__symbol__"):
return React58.createElement(SymbolNode, { ...props, ...value2.__symbol__ });
case Object.prototype.hasOwnProperty.call(value2, "__element__"):
return React58.createElement(ElementNode, { ...props, ...value2.__element__ });
case Object.prototype.hasOwnProperty.call(value2, "__class__"):
return React58.createElement(ClassNode, { ...props, ...value2.__class__ });
case Object.prototype.hasOwnProperty.call(value2, "__callId__"):
return React58.createElement(MethodCall, { call: callsById?.get(value2.__callId__), callsById });
case Object.prototype.toString.call(value2) === "[object Object]":
return React58.createElement(
ObjectNode,
{
value: value2,
showInspector: showObjectInspector,
callsById,
...props
}
);
default:
return React58.createElement(OtherNode, { value: value2, ...props });
}
}, "Node");
var NullNode = /* @__PURE__ */ __name((props) => {
const colors = useThemeColors();
return React58.createElement("span", { style: { color: colors.nullish }, ...props }, "null");
}, "NullNode");
var UndefinedNode = /* @__PURE__ */ __name((props) => {
const colors = useThemeColors();
return React58.createElement("span", { style: { color: colors.nullish }, ...props }, "undefined");
}, "UndefinedNode");
var StringNode = /* @__PURE__ */ __name(({ value: value2, ...props }) => {
const colors = useThemeColors();
return React58.createElement("span", { style: { color: colors.string }, ...props }, JSON.stringify(ellipsize(value2, 50)));
}, "StringNode");
var NumberNode = /* @__PURE__ */ __name(({ value: value2, ...props }) => {
const colors = useThemeColors();
return React58.createElement("span", { style: { color: colors.number }, ...props }, value2);
}, "NumberNode");
var BooleanNode = /* @__PURE__ */ __name(({ value: value2, ...props }) => {
const colors = useThemeColors();
return React58.createElement("span", { style: { color: colors.boolean }, ...props }, String(value2));
}, "BooleanNode");
var ArrayNode = /* @__PURE__ */ __name(({
value: value2,
nested = false,
callsById
}) => {
const colors = useThemeColors();
if (nested) {
return React58.createElement("span", { style: { color: colors.base } }, "[\u2026]");
}
const nodes = value2.slice(0, 3).map((v2, index) => React58.createElement(Node2, { key: `${index}--${JSON.stringify(v2)}`, value: v2, nested: true, callsById }));
const nodelist = interleave(nodes, React58.createElement("span", null, ", "));
if (value2.length <= 3) {
return React58.createElement("span", { style: { color: colors.base } }, "[", nodelist, "]");
}
return React58.createElement("span", { style: { color: colors.base } }, "(", value2.length, ") [", nodelist, ", \u2026]");
}, "ArrayNode");
var ObjectNode = /* @__PURE__ */ __name(({
showInspector,
value: value2,
callsById,
nested = false
}) => {
const isDarkMode = useTheme5().base === "dark";
const colors = useThemeColors();
if (showInspector) {
return React58.createElement(React58.Fragment, null, React58.createElement(
ObjectInspector2,
{
id: "interactions-object-inspector",
data: value2,
includePrototypes: false,
colorScheme: isDarkMode ? "dark" : "light"
}
));
}
if (nested) {
return React58.createElement("span", { style: { color: colors.base } }, "{\u2026}");
}
const nodelist = interleave(
Object.entries(value2).slice(0, 2).map(([k2, v2]) => React58.createElement(Fragment2, { key: k2 }, React58.createElement("span", { style: { color: colors.objectkey } }, k2, ": "), React58.createElement(Node2, { value: v2, callsById, nested: true }))),
React58.createElement("span", null, ", ")
);
if (Object.keys(value2).length <= 2) {
return React58.createElement("span", { style: { color: colors.base } }, "{ ", nodelist, " }");
}
return React58.createElement("span", { style: { color: colors.base } }, "(", Object.keys(value2).length, ") ", "{ ", nodelist, ", \u2026 }");
}, "ObjectNode");
var ClassNode = /* @__PURE__ */ __name(({ name }) => {
const colors = useThemeColors();
return React58.createElement("span", { style: { color: colors.instance } }, name);
}, "ClassNode");
var FunctionNode = /* @__PURE__ */ __name(({ name }) => {
const colors = useThemeColors();
return name ? React58.createElement("span", { style: { color: colors.function } }, name) : React58.createElement("span", { style: { color: colors.nullish, fontStyle: "italic" } }, "anonymous");
}, "FunctionNode");
var ElementNode = /* @__PURE__ */ __name(({
prefix,
localName,
id,
classNames = [],
innerText
}) => {
const name = prefix ? `${prefix}:${localName}` : localName;
const colors = useThemeColors();
return React58.createElement("span", { style: { wordBreak: "keep-all" } }, React58.createElement("span", { key: `${name}_lt`, style: { color: colors.muted } }, "<"), React58.createElement("span", { key: `${name}_tag`, style: { color: colors.tag.name } }, name), React58.createElement("span", { key: `${name}_suffix`, style: { color: colors.tag.suffix } }, id ? `#${id}` : classNames.reduce((acc, className) => `${acc}.${className}`, "")), React58.createElement("span", { key: `${name}_gt`, style: { color: colors.muted } }, ">"), !id && classNames.length === 0 && innerText && React58.createElement(React58.Fragment, null, React58.createElement("span", { key: `${name}_text` }, innerText), React58.createElement("span", { key: `${name}_close_lt`, style: { color: colors.muted } }, "<"), React58.createElement("span", { key: `${name}_close_tag`, style: { color: colors.tag.name } }, "/", name), React58.createElement("span", { key: `${name}_close_gt`, style: { color: colors.muted } }, ">")));
}, "ElementNode");
var DateNode = /* @__PURE__ */ __name(({ value: value2 }) => {
let parsed = new Date(value2);
if (isNaN(Number(parsed))) {
logger4.warn("Invalid date value:", value2);
parsed = null;
}
const colors = useThemeColors();
if (!parsed) {
return React58.createElement("span", { style: { whiteSpace: "nowrap", color: colors.date } }, "Invalid date");
}
const [date, time, ms] = parsed.toISOString().split(/[T.Z]/);
return React58.createElement("span", { style: { whiteSpace: "nowrap", color: colors.date } }, date, React58.createElement("span", { style: { opacity: 0.7 } }, "T"), time === "00:00:00" ? React58.createElement("span", { style: { opacity: 0.7 } }, time) : time, ms === "000" ? React58.createElement("span", { style: { opacity: 0.7 } }, ".", ms) : `.${ms}`, React58.createElement("span", { style: { opacity: 0.7 } }, "Z"));
}, "DateNode");
var ErrorNode = /* @__PURE__ */ __name(({ name, message }) => {
const colors = useThemeColors();
return React58.createElement("span", { style: { color: colors.error.name } }, name, message && ": ", message && React58.createElement("span", { style: { color: colors.error.message }, title: message.length > 50 ? message : "" }, ellipsize(message, 50)));
}, "ErrorNode");
var RegExpNode = /* @__PURE__ */ __name(({ flags, source }) => {
const colors = useThemeColors();
return React58.createElement("span", { style: { whiteSpace: "nowrap", color: colors.regex.flags } }, "/", React58.createElement("span", { style: { color: colors.regex.source } }, source), "/", flags);
}, "RegExpNode");
var SymbolNode = /* @__PURE__ */ __name(({ description }) => {
const colors = useThemeColors();
return React58.createElement("span", { style: { whiteSpace: "nowrap", color: colors.instance } }, "Symbol(", description && React58.createElement("span", { style: { color: colors.meta } }, '"', description, '"'), ")");
}, "SymbolNode");
var OtherNode = /* @__PURE__ */ __name(({ value: value2 }) => {
const colors = useThemeColors();
return React58.createElement("span", { style: { color: colors.meta } }, stringify(value2));
}, "OtherNode");
var StepNode = /* @__PURE__ */ __name(({ label }) => {
const colors = useThemeColors();
const { typography: typography4 } = useTheme5();
return React58.createElement(
"span",
{
style: {
color: colors.base,
fontFamily: typography4.fonts.base,
fontSize: typography4.size.s2 - 1
}
},
label
);
}, "StepNode");
var MethodCall = /* @__PURE__ */ __name(({
call,
callsById
}) => {
if (!call) {
return null;
}
if (call.method === "step" && call.path?.length === 0) {
return React58.createElement(StepNode, { label: call.args[0] });
}
const path = call.path?.flatMap((elem, index) => {
const callId = elem.__callId__;
return [
callId ? React58.createElement(MethodCall, { key: `elem${index}`, call: callsById?.get(callId), callsById }) : React58.createElement("span", { key: `elem${index}` }, elem),
React58.createElement("wbr", { key: `wbr${index}` }),
React58.createElement("span", { key: `dot${index}` }, ".")
];
});
const args = call.args?.flatMap((arg, index, array2) => {
const node = React58.createElement(Node2, { key: `node${index}`, value: arg, callsById });
return index < array2.length - 1 ? [node, React58.createElement("span", { key: `comma${index}` }, ",\xA0"), React58.createElement("wbr", { key: `wbr${index}` })] : [node];
});
const colors = useThemeColors();
return React58.createElement(React58.Fragment, null, React58.createElement("span", { style: { color: colors.base } }, path), React58.createElement("span", { style: { color: colors.method } }, call.method), React58.createElement("span", { style: { color: colors.base } }, "(", React58.createElement("wbr", null), args, React58.createElement("wbr", null), ")"));
}, "MethodCall");
// src/component-testing/components/MatcherResult.tsx
var getParams = /* @__PURE__ */ __name((line, fromIndex = 0) => {
for (let i2 = fromIndex, depth = 1; i2 < line.length; i2 += 1) {
if (line[i2] === "(") {
depth += 1;
} else if (line[i2] === ")") {
depth -= 1;
}
if (depth === 0) {
return line.slice(fromIndex, i2);
}
}
return "";
}, "getParams");
var parseValue = /* @__PURE__ */ __name((value2) => {
try {
return value2 === "undefined" ? void 0 : JSON.parse(value2);
} catch (e2) {
return value2;
}
}, "parseValue");
var StyledExpected = styled35.span(({ theme: theme3 }) => ({
color: theme3.base === "light" ? theme3.color.positiveText : theme3.color.positive
}));
var StyledReceived = styled35.span(({ theme: theme3 }) => ({
color: theme3.base === "light" ? theme3.color.negativeText : theme3.color.negative
}));
var Received = /* @__PURE__ */ __name(({ value: value2, parsed }) => parsed ? React59.createElement(Node2, { showObjectInspector: true, value: value2, style: { color: "#D43900" } }) : React59.createElement(StyledReceived, null, value2), "Received");
var Expected = /* @__PURE__ */ __name(({ value: value2, parsed }) => {
if (parsed) {
if (typeof value2 === "string" && value2.startsWith("called with")) {
return React59.createElement(React59.Fragment, null, value2);
}
return React59.createElement(Node2, { showObjectInspector: true, value: value2, style: { color: "#16B242" } });
}
return React59.createElement(StyledExpected, null, value2);
}, "Expected");
var MatcherResult = /* @__PURE__ */ __name(({
message,
style = {}
}) => {
const filter = useAnsiToHtmlFilter();
const lines = message.split("\n");
return React59.createElement(
"pre",
{
style: {
margin: 0,
padding: "8px 10px 8px 36px",
fontSize: typography.size.s1,
...style
}
},
lines.flatMap((line, index) => {
if (line.startsWith("expect(")) {
const received = getParams(line, 7);
const remainderIndex = received ? 7 + received.length : 0;
const matcher = received && line.slice(remainderIndex).match(/\.(to|last|nth)[A-Z]\w+\(/);
if (matcher) {
const expectedIndex = remainderIndex + (matcher.index ?? 0) + matcher[0].length;
const expected = getParams(line, expectedIndex);
if (expected) {
return [
"expect(",
React59.createElement(Received, { key: `received_${received}`, value: received }),
line.slice(remainderIndex, expectedIndex),
React59.createElement(Expected, { key: `expected_${expected}`, value: expected }),
line.slice(expectedIndex + expected.length),
React59.createElement("br", { key: `br${index}` })
];
}
}
}
if (line.match(/^\s*- /)) {
return [React59.createElement(Expected, { key: line + index, value: line }), React59.createElement("br", { key: `br${index}` })];
}
if (line.match(/^\s*\+ /) || line.match(/^Received: $/)) {
return [React59.createElement(Received, { key: line + index, value: line }), React59.createElement("br", { key: `br${index}` })];
}
const [, assertionLabel, assertionValue] = line.match(/^(Expected|Received): (.*)$/) || [];
if (assertionLabel && assertionValue) {
return assertionLabel === "Expected" ? [
"Expected: ",
React59.createElement(Expected, { key: line + index, value: parseValue(assertionValue), parsed: true }),
React59.createElement("br", { key: `br${index}` })
] : [
"Received: ",
React59.createElement(Received, { key: line + index, value: parseValue(assertionValue), parsed: true }),
React59.createElement("br", { key: `br${index}` })
];
}
const [, prefix, numberOfCalls] = line.match(/(Expected number|Received number|Number) of calls: (\d+)$/i) || [];
if (prefix && numberOfCalls) {
return [
`${prefix} of calls: `,
React59.createElement(Node2, { key: line + index, value: Number(numberOfCalls) }),
React59.createElement("br", { key: `br${index}` })
];
}
const [, receivedValue] = line.match(/^Received has value: (.+)$/) || [];
if (receivedValue) {
return [
"Received has value: ",
React59.createElement(Node2, { key: line + index, value: parseValue(receivedValue) }),
React59.createElement("br", { key: `br${index}` })
];
}
return [
React59.createElement(
"span",
{
key: line + index,
dangerouslySetInnerHTML: { __html: filter.toHtml(line) }
}
),
React59.createElement("br", { key: `br${index}` })
];
})
);
}, "MatcherResult");
// src/component-testing/components/StatusIcon.tsx
import React60 from "react";
import { CheckIcon as CheckIcon2, CircleIcon, PlayIcon, StopAltIcon } from "@storybook/icons";
import { styled as styled36, useTheme as useTheme6 } from "storybook/theming";
var WarningContainer = styled36.div({
width: 14,
height: 14,
display: "flex",
alignItems: "center",
justifyContent: "center"
});
var StatusIcon = /* @__PURE__ */ __name(({ status }) => {
const theme3 = useTheme6();
switch (status) {
case "done" /* DONE */: {
return React60.createElement(CheckIcon2, { color: theme3.color.positive, "data-testid": "icon-done" });
}
case "error" /* ERROR */: {
return React60.createElement(StopAltIcon, { color: theme3.color.negative, "data-testid": "icon-error" });
}
case "active" /* ACTIVE */: {
return React60.createElement(PlayIcon, { color: theme3.color.secondary, "data-testid": "icon-active" });
}
case "waiting" /* WAITING */: {
return React60.createElement(WarningContainer, { "data-testid": "icon-waiting" }, React60.createElement(CircleIcon, { color: curriedTransparentize$1(0.5, "#CCCCCC"), size: 6 }));
}
default: {
return null;
}
}
}, "StatusIcon");
// src/component-testing/components/Interaction.tsx
var MethodCallWrapper = styled37.div({
fontFamily: typography2.fonts.mono,
fontSize: typography2.size.s1,
overflowWrap: "break-word",
inlineSize: "calc( 100% - 40px )"
});
var RowContainer = styled37("div", {
shouldForwardProp: /* @__PURE__ */ __name((prop) => !["call", "pausedAt"].includes(prop.toString()), "shouldForwardProp")
})(
({ theme: theme3, call }) => ({
position: "relative",
display: "flex",
flexDirection: "column",
borderBottom: `1px solid ${theme3.appBorderColor}`,
fontFamily: typography2.fonts.base,
fontSize: 13,
...call.status === "error" /* ERROR */ && {
backgroundColor: theme3.base === "dark" ? curriedTransparentize$1(0.93, theme3.color.negative) : theme3.background.warning
},
paddingLeft: (call.ancestors?.length ?? 0) * 20
}),
({ theme: theme3, call, pausedAt }) => pausedAt === call.id && {
"&::before": {
content: '""',
position: "absolute",
top: -5,
zIndex: 1,
borderTop: "4.5px solid transparent",
borderLeft: `7px solid ${theme3.color.warning}`,
borderBottom: "4.5px solid transparent"
},
"&::after": {
content: '""',
position: "absolute",
top: -1,
zIndex: 1,
width: "100%",
borderTop: `1.5px solid ${theme3.color.warning}`
}
}
);
var RowHeader = styled37.div(({ theme: theme3, isInteractive }) => ({
display: "flex",
"&:hover": isInteractive ? {} : { background: theme3.background.hoverable }
}));
var RowLabel = styled37("button", {
shouldForwardProp: /* @__PURE__ */ __name((prop) => !["call"].includes(prop.toString()), "shouldForwardProp")
})(({ theme: theme3, disabled, call }) => ({
flex: 1,
display: "grid",
background: "none",
border: 0,
gridTemplateColumns: "15px 1fr",
alignItems: "center",
minHeight: 40,
margin: 0,
padding: "8px 15px",
textAlign: "start",
cursor: disabled || call.status === "error" /* ERROR */ ? "default" : "pointer",
"&:focus-visible": {
outline: 0,
boxShadow: `inset 3px 0 0 0 ${call.status === "error" /* ERROR */ ? theme3.color.warning : theme3.color.secondary}`,
background: call.status === "error" /* ERROR */ ? "transparent" : theme3.background.hoverable
},
"& > div": {
opacity: call.status === "waiting" /* WAITING */ ? 0.5 : 1
}
}));
var RowActions = styled37.div({
display: "flex",
alignItems: "center",
padding: 6
});
var StyledIconButton = styled37(IconButton5)(({ theme: theme3 }) => ({
color: theme3.textMutedColor,
margin: "0 3px"
}));
var Note = styled37(TooltipNote2)(({ theme: theme3 }) => ({
fontFamily: theme3.typography.fonts.base
}));
var RowMessage = styled37("div")(({ theme: theme3 }) => ({
padding: "8px 10px 8px 36px",
fontSize: typography2.size.s1,
color: theme3.color.defaultText,
pre: {
margin: 0,
padding: 0
}
}));
var ErrorName = styled37.span(({ theme: theme3 }) => ({
color: theme3.base === "dark" ? "#5EC1FF" : "#0271B6"
}));
var ErrorMessage2 = styled37.span(({ theme: theme3 }) => ({
color: theme3.base === "dark" ? "#eee" : "#444"
}));
var ErrorExplainer = styled37.p(({ theme: theme3 }) => ({
color: theme3.base === "dark" ? theme3.color.negative : theme3.color.negativeText,
fontSize: theme3.typography.size.s2,
maxWidth: 500,
textWrap: "balance"
}));
var Exception = /* @__PURE__ */ __name(({ exception }) => {
const filter = useAnsiToHtmlFilter();
if (!exception) {
return null;
}
if (exception.callId === INTERNAL_RENDER_CALL_ID) {
return React61.createElement(RowMessage, null, React61.createElement("pre", null, React61.createElement(ErrorName, null, exception.name, ":"), " ", React61.createElement(ErrorMessage2, null, exception.message)), React61.createElement(ErrorExplainer, null, "The component failed to render properly. Automated component tests will not run until this is resolved. Check the full error message in Storybook\u2019s canvas to debug."));
}
if (isJestError(exception)) {
return React61.createElement(MatcherResult, { ...exception });
}
if (isChaiError(exception)) {
return React61.createElement(RowMessage, null, React61.createElement(
MatcherResult,
{
message: `${exception.message}${exception.diff ? `
${exception.diff}` : ""}`,
style: { padding: 0 }
}
), React61.createElement("p", null, "See the full stack trace in the browser console."));
}
const paragraphs = exception.message.split("\n\n");
const more = paragraphs.length > 1;
return React61.createElement(RowMessage, null, React61.createElement("pre", { dangerouslySetInnerHTML: { __html: filter.toHtml(paragraphs[0]) } }), more && React61.createElement("p", null, "See the full stack trace in the browser console."));
}, "Exception");
var Interaction = /* @__PURE__ */ __name(({
call,
callsById,
controls,
controlStates,
childCallIds,
isHidden,
isCollapsed,
toggleCollapsed,
pausedAt
}) => {
const [isHovered, setIsHovered] = React61.useState(false);
const isInteractive = !controlStates.goto || !call.interceptable || !!call.ancestors?.length;
if (isHidden) {
return null;
}
if (call.id === INTERNAL_RENDER_CALL_ID) {
return null;
}
return React61.createElement(RowContainer, { call, pausedAt }, React61.createElement(RowHeader, { isInteractive }, React61.createElement(
RowLabel,
{
"aria-label": "Interaction step",
call,
onClick: () => controls.goto(call.id),
disabled: isInteractive,
onMouseEnter: () => controlStates.goto && setIsHovered(true),
onMouseLeave: () => controlStates.goto && setIsHovered(false)
},
React61.createElement(StatusIcon, { status: isHovered ? "active" /* ACTIVE */ : call.status }),
React61.createElement(MethodCallWrapper, { style: { marginLeft: 6, marginBottom: 1 } }, React61.createElement(MethodCall, { call, callsById }))
), React61.createElement(RowActions, null, (childCallIds?.length ?? 0) > 0 && React61.createElement(
WithTooltip2,
{
hasChrome: false,
tooltip: React61.createElement(Note, { note: `${isCollapsed ? "Show" : "Hide"} interactions` })
},
React61.createElement(
StyledIconButton,
{
onClick: toggleCollapsed,
"aria-label": isCollapsed ? "Expand interaction" : "Collapse interaction"
},
isCollapsed ? React61.createElement(ChevronDownIcon3, null) : React61.createElement(ChevronUpIcon2, null)
)
))), call.status === "error" /* ERROR */ && call.exception?.callId === call.id && React61.createElement(Exception, { exception: call.exception }));
}, "Interaction");
// src/component-testing/components/Subnav.tsx
import React64 from "react";
import {
Bar as Bar3,
Button as Button6,
IconButton as IconButton6,
P as P2,
Separator,
TooltipNote as TooltipNote4,
WithTooltip as WithTooltip4
} from "storybook/internal/components";
import {
FastForwardIcon,
PlayBackIcon,
PlayNextIcon,
RewindIcon,
SyncIcon
} from "@storybook/icons";
import { styled as styled39, useTheme as useTheme7 } from "storybook/theming";
// src/component-testing/components/StatusBadge.tsx
import React63 from "react";
import { TooltipNote as TooltipNote3, WithTooltip as WithTooltip3 } from "storybook/internal/components";
import { styled as styled38, typography as typography3 } from "storybook/theming";
var StatusColorMapping = {
rendering: "mediumdark",
playing: "warning",
completed: "positive",
errored: "negative",
aborted: "purple"
};
var StatusTextMapping = {
rendering: "Wait",
playing: "Runs",
completed: "Pass",
errored: "Fail",
aborted: "Bail"
};
var StatusNoteMapping = {
rendering: "Story is rendering",
playing: "Interactions are running",
completed: "Story ran successfully",
errored: "Story failed to complete",
aborted: "Interactions aborted due to file changes"
};
var StyledBadge = styled38.div(({ theme: theme3, status }) => {
const backgroundColor = theme3.color[StatusColorMapping[status]];
return {
display: "inline-block",
padding: "4px 6px 4px 8px",
borderRadius: "4px",
backgroundColor,
color: "white",
fontFamily: typography3.fonts.base,
textTransform: "uppercase",
fontSize: typography3.size.s1,
letterSpacing: 3,
fontWeight: typography3.weight.bold,
minWidth: 65,
textAlign: "center"
};
});
var StatusBadge = /* @__PURE__ */ __name(({ status }) => {
const badgeText = StatusTextMapping[status];
const badgeNote = StatusNoteMapping[status];
return React63.createElement(
WithTooltip3,
{
hasChrome: false,
placement: "top",
trigger: "hover",
tooltip: React63.createElement(TooltipNote3, { note: badgeNote })
},
React63.createElement(StyledBadge, { "aria-label": "Story status", status }, badgeText)
);
}, "StatusBadge");
// src/component-testing/components/Subnav.tsx
var SubnavWrapper = styled39.div(({ theme: theme3 }) => ({
boxShadow: `${theme3.appBorderColor} 0 -1px 0 0 inset`,
background: theme3.background.app,
position: "sticky",
top: 0,
zIndex: 1
}));
var StyledSubnav = styled39.nav({
height: 39,
display: "flex",
alignItems: "center",
justifyContent: "space-between",
paddingLeft: 15
});
var StyledButton = styled39(Button6)(({ theme: theme3 }) => ({
borderRadius: 4,
padding: 6,
color: theme3.textMutedColor,
"&:not(:disabled)": {
"&:hover,&:focus-visible": {
color: theme3.color.secondary
}
}
}));
var Note2 = styled39(TooltipNote4)(({ theme: theme3 }) => ({
fontFamily: theme3.typography.fonts.base
}));
var StyledIconButton2 = styled39(IconButton6)(({ theme: theme3 }) => ({
color: theme3.textMutedColor,
margin: "0 3px"
}));
var StyledSeparator = styled39(Separator)({
marginTop: 0
});
var StyledLocation = styled39(P2)(({ theme: theme3, isText }) => ({
color: isText ? theme3.textMutedColor : theme3.color.secondary,
cursor: isText ? "default" : "pointer",
fontWeight: isText ? theme3.typography.weight.regular : theme3.typography.weight.bold,
justifyContent: "flex-end",
textAlign: "right",
whiteSpace: "nowrap",
marginTop: "auto",
marginBottom: 1,
paddingRight: 15,
fontSize: 13
}));
var Group = styled39.div({
display: "flex",
alignItems: "center"
});
var RewindButton = styled39(StyledIconButton2)({
marginLeft: 9
});
var JumpToEndButton = styled39(StyledButton)({
marginLeft: 9,
marginRight: 9,
lineHeight: "12px"
});
var RerunButton = styled39(StyledIconButton2)(({ theme: theme3, animating, disabled }) => ({
opacity: disabled ? 0.5 : 1,
svg: {
animation: animating ? `${theme3.animation.rotate360} 200ms ease-out` : void 0
}
}));
var Subnav = /* @__PURE__ */ __name(({
controls,
controlStates,
status,
storyFileName,
onScrollToEnd,
importPath,
canOpenInEditor,
api
}) => {
const buttonText = status === "errored" ? "Scroll to error" : "Scroll to end";
const theme3 = useTheme7();
return React64.createElement(SubnavWrapper, null, React64.createElement(Bar3, { backgroundColor: theme3.background.app }, React64.createElement(StyledSubnav, { "aria-label": "Component tests toolbar" }, React64.createElement(Group, null, React64.createElement(StatusBadge, { status }), React64.createElement(JumpToEndButton, { onClick: onScrollToEnd, disabled: !onScrollToEnd }, buttonText), React64.createElement(StyledSeparator, null), React64.createElement(WithTooltip4, { trigger: "hover", hasChrome: false, tooltip: React64.createElement(Note2, { note: "Go to start" }) }, React64.createElement(
RewindButton,
{
"aria-label": "Go to start",
onClick: controls.start,
disabled: !controlStates.start
},
React64.createElement(RewindIcon, null)
)), React64.createElement(WithTooltip4, { trigger: "hover", hasChrome: false, tooltip: React64.createElement(Note2, { note: "Go back" }) }, React64.createElement(
StyledIconButton2,
{
"aria-label": "Go back",
onClick: controls.back,
disabled: !controlStates.back
},
React64.createElement(PlayBackIcon, null)
)), React64.createElement(WithTooltip4, { trigger: "hover", hasChrome: false, tooltip: React64.createElement(Note2, { note: "Go forward" }) }, React64.createElement(
StyledIconButton2,
{
"aria-label": "Go forward",
onClick: controls.next,
disabled: !controlStates.next
},
React64.createElement(PlayNextIcon, null)
)), React64.createElement(WithTooltip4, { trigger: "hover", hasChrome: false, tooltip: React64.createElement(Note2, { note: "Go to end" }) }, React64.createElement(
StyledIconButton2,
{
"aria-label": "Go to end",
onClick: controls.end,
disabled: !controlStates.end
},
React64.createElement(FastForwardIcon, null)
)), React64.createElement(WithTooltip4, { trigger: "hover", hasChrome: false, tooltip: React64.createElement(Note2, { note: "Rerun" }) }, React64.createElement(RerunButton, { "aria-label": "Rerun", onClick: controls.rerun }, React64.createElement(SyncIcon, null)))), (importPath || storyFileName) && React64.createElement(Group, null, canOpenInEditor ? React64.createElement(
WithTooltip4,
{
trigger: "hover",
hasChrome: false,
tooltip: React64.createElement(Note2, { note: "Open in editor" })
},
React64.createElement(
StyledLocation,
{
"aria-label": "Open in editor",
onClick: () => {
api.openInEditor({
file: importPath
});
}
},
storyFileName
)
) : React64.createElement(StyledLocation, { isText: true }, storyFileName)))));
}, "Subnav");
// src/component-testing/components/TestDiscrepancyMessage.tsx
import React65 from "react";
import { Link as Link6 } from "storybook/internal/components";
import { useStorybookApi as useStorybookApi5 } from "storybook/manager-api";
import { styled as styled40 } from "storybook/theming";
var Wrapper12 = styled40.div(({ theme: { color: color2, typography: typography4, background } }) => ({
textAlign: "start",
padding: "11px 15px",
fontSize: `${typography4.size.s2 - 1}px`,
fontWeight: typography4.weight.regular,
lineHeight: "1rem",
background: background.app,
borderBottom: `1px solid ${color2.border}`,
color: color2.defaultText,
backgroundClip: "padding-box",
position: "relative",
code: {
fontSize: `${typography4.size.s1 - 1}px`,
color: "inherit",
margin: "0 0.2em",
padding: "0 0.2em",
background: "rgba(255, 255, 255, 0.8)",
borderRadius: "2px",
boxShadow: "0 0 0 1px rgba(0, 0, 0, 0.1)"
}
}));
var TestDiscrepancyMessage = /* @__PURE__ */ __name(({ browserTestStatus }) => {
const api = useStorybookApi5();
const docsUrl = api.getDocsUrl({
subpath: DOCUMENTATION_DISCREPANCY_LINK,
versioned: true,
renderer: true
});
const [passed, failed] = browserTestStatus === "error" /* ERROR */ ? ["the CLI", "this browser"] : ["this browser", "the CLI"];
return React65.createElement(Wrapper12, null, "This interaction test passed in ", passed, ", but the tests failed in ", failed, ".", " ", React65.createElement(Link6, { href: docsUrl, target: "_blank", withArrow: true }, "Learn what could cause this"));
}, "TestDiscrepancyMessage");
// src/component-testing/components/InteractionsPanel.tsx
var Container3 = styled41.div(({ theme: theme3 }) => ({
height: "100%",
background: theme3.background.content
}));
var CaughtException = styled41.div(({ theme: theme3 }) => ({
borderBottom: `1px solid ${theme3.appBorderColor}`,
backgroundColor: theme3.base === "dark" ? curriedTransparentize$1(0.93, theme3.color.negative) : theme3.background.warning,
padding: 15,
fontSize: theme3.typography.size.s2 - 1,
lineHeight: "19px"
}));
var CaughtExceptionCode = styled41.code(({ theme: theme3 }) => ({
margin: "0 1px",
padding: 3,
fontSize: theme3.typography.size.s1 - 1,
lineHeight: 1,
verticalAlign: "top",
background: "rgba(0, 0, 0, 0.05)",
border: `1px solid ${theme3.appBorderColor}`,
borderRadius: 3
}));
var CaughtExceptionTitle = styled41.div({
paddingBottom: 4,
fontWeight: "bold"
});
var CaughtExceptionDescription = styled41.p({
margin: 0,
padding: "0 0 20px"
});
var CaughtExceptionStack = styled41.pre(({ theme: theme3 }) => ({
margin: 0,
padding: 0,
"&:not(:last-child)": {
paddingBottom: 16
},
fontSize: theme3.typography.size.s1 - 1
}));
var InteractionsPanel = React66.memo(
/* @__PURE__ */ __name(function InteractionsPanel2({
storyUrl,
status,
calls,
controls,
controlStates,
interactions,
fileName,
hasException,
caughtException,
unhandledErrors,
pausedAt,
onScrollToEnd,
endRef,
hasResultMismatch,
browserTestStatus,
importPath,
canOpenInEditor,
api
}) {
const filter = useAnsiToHtmlFilter();
const hasRealInteractions = interactions.some((i2) => i2.id !== INTERNAL_RENDER_CALL_ID);
return React66.createElement(Container3, null, hasResultMismatch && React66.createElement(TestDiscrepancyMessage, { browserTestStatus }), controlStates.detached && (hasRealInteractions || hasException) && React66.createElement(DetachedDebuggerMessage, { storyUrl }), React66.createElement(
Subnav,
{
controls,
controlStates,
status,
storyFileName: fileName,
onScrollToEnd,
importPath,
canOpenInEditor,
api
}
), React66.createElement("div", { "aria-label": "Interactions list" }, interactions.map((call) => React66.createElement(
Interaction,
{
key: call.id,
call,
callsById: calls,
controls,
controlStates,
childCallIds: call.childCallIds,
isHidden: call.isHidden,
isCollapsed: call.isCollapsed,
toggleCollapsed: call.toggleCollapsed,
pausedAt
}
))), caughtException && !isTestAssertionError(caughtException) && React66.createElement(CaughtException, null, React66.createElement(CaughtExceptionTitle, null, "Caught exception in ", React66.createElement(CaughtExceptionCode, null, "play"), " function"), React66.createElement(
CaughtExceptionStack,
{
"data-chromatic": "ignore",
dangerouslySetInnerHTML: {
__html: filter.toHtml(printSerializedError(caughtException))
}
}
)), unhandledErrors && React66.createElement(CaughtException, null, React66.createElement(CaughtExceptionTitle, null, "Unhandled Errors"), React66.createElement(CaughtExceptionDescription, null, "Found ", unhandledErrors.length, " unhandled error", unhandledErrors.length > 1 ? "s" : "", " ", "while running the play function. This might cause false positive assertions. Resolve unhandled errors or ignore unhandled errors with setting the", React66.createElement(CaughtExceptionCode, null, "test.dangerouslyIgnoreUnhandledErrors"), " ", "parameter to ", React66.createElement(CaughtExceptionCode, null, "true"), "."), unhandledErrors.map((error, i2) => React66.createElement(CaughtExceptionStack, { key: i2, "data-chromatic": "ignore" }, printSerializedError(error)))), React66.createElement("div", { ref: endRef }), status === "completed" && !caughtException && !hasRealInteractions && React66.createElement(Empty2, null));
}, "InteractionsPanel")
);
function printSerializedError(error) {
return error.stack || `${error.name}: ${error.message}`;
}
__name(printSerializedError, "printSerializedError");
// src/component-testing/components/Panel.tsx
var INITIAL_CONTROL_STATES = {
detached: false,
start: false,
back: false,
goto: false,
next: false,
end: false
};
var playStatusMap = {
rendering: "rendering",
playing: "playing",
completed: "completed",
errored: "errored",
aborted: "aborted"
};
var terminalStatuses = ["completed", "errored", "aborted"];
var storyStatusMap = {
["done" /* DONE */]: "status-value:success",
["error" /* ERROR */]: "status-value:error",
["active" /* ACTIVE */]: "status-value:pending",
["waiting" /* WAITING */]: "status-value:pending"
};
var getInteractions = /* @__PURE__ */ __name(({
log,
calls,
collapsed,
setCollapsed
}) => {
const callsById = /* @__PURE__ */ new Map();
const childCallMap = /* @__PURE__ */ new Map();
const interactions = log.map(({ callId, ancestors, status }) => {
let isHidden = false;
ancestors.forEach((ancestor) => {
if (collapsed.has(ancestor)) {
isHidden = true;
}
childCallMap.set(ancestor, (childCallMap.get(ancestor) || []).concat(callId));
});
return { ...calls.get(callId), status, isHidden };
}).map((call) => {
const status = call.status === "error" /* ERROR */ && call.ancestors && callsById.get(call.ancestors.slice(-1)[0])?.status === "active" /* ACTIVE */ ? "active" /* ACTIVE */ : call.status;
callsById.set(call.id, { ...call, status });
return {
...call,
status,
childCallIds: childCallMap.get(call.id),
isCollapsed: collapsed.has(call.id),
toggleCollapsed: /* @__PURE__ */ __name(() => setCollapsed((ids) => {
if (ids.has(call.id)) {
ids.delete(call.id);
} else {
ids.add(call.id);
}
return new Set(ids);
}), "toggleCollapsed")
};
});
return interactions;
}, "getInteractions");
var getPanelState = /* @__PURE__ */ __name((state, {
log,
calls,
collapsed,
setCollapsed
}) => getInteractions({ log, calls, collapsed, setCollapsed }).reduce(
(acc, interaction) => {
if (interaction.id === INTERNAL_RENDER_CALL_ID) {
acc.interactions.push(interaction);
} else if (state.status !== "rendering") {
acc.controlStates = state.controlStates;
acc.interactions.push(interaction);
if (interaction.method !== "step") {
acc.interactionsCount++;
}
}
return acc;
},
{
...state,
controlStates: INITIAL_CONTROL_STATES,
interactions: [],
interactionsCount: 0
}
), "getPanelState");
var getInternalRenderCall = /* @__PURE__ */ __name((storyId, exception) => ({
id: INTERNAL_RENDER_CALL_ID,
method: "render",
args: [],
cursor: 0,
storyId,
ancestors: [],
path: [],
interceptable: true,
retain: false,
exception
}), "getInternalRenderCall");
var getInternalRenderLogItem = /* @__PURE__ */ __name((status) => ({
callId: INTERNAL_RENDER_CALL_ID,
status,
ancestors: []
}), "getInternalRenderLogItem");
var Panel = memo4(
/* @__PURE__ */ __name(function PanelMemoized({ refId, storyId, storyUrl }) {
const { statusValue, testRunId } = experimental_useStatusStore((state2) => {
const storyStatus = refId ? void 0 : state2[storyId]?.[STATUS_TYPE_ID_COMPONENT_TEST];
return {
statusValue: storyStatus?.value,
testRunId: storyStatus?.data?.testRunId
};
});
const state = useStorybookState2();
const api = useStorybookApi6();
const data = api.getData(state.storyId, state.refId);
const importPath = data?.importPath;
const canOpenInEditor = global2.CONFIG_TYPE === "DEVELOPMENT" && !state.refId;
const [panelState, set] = useAddonState2(ADDON_ID7, {
status: "rendering",
controlStates: INITIAL_CONTROL_STATES,
interactions: [],
interactionsCount: 0,
hasException: false,
pausedAt: void 0,
caughtException: void 0,
unhandledErrors: void 0
});
const [scrollTarget, setScrollTarget] = useState23(void 0);
const [collapsed, setCollapsed] = useState23(/* @__PURE__ */ new Set());
const [hasResultMismatch, setResultMismatch] = useState23(false);
const {
status = "rendering",
controlStates = INITIAL_CONTROL_STATES,
interactions = [],
pausedAt = void 0,
caughtException = void 0,
unhandledErrors = void 0
} = panelState;
const log = useRef7([getInternalRenderLogItem("active" /* ACTIVE */)]);
const calls = useRef7(
/* @__PURE__ */ new Map([[INTERNAL_RENDER_CALL_ID, getInternalRenderCall(storyId)]])
);
const setCall = /* @__PURE__ */ __name(({ status: status2, ...call }) => calls.current.set(call.id, call), "setCall");
const endRef = useRef7();
useEffect18(() => {
let observer;
if (global2.IntersectionObserver) {
observer = new global2.IntersectionObserver(
([end]) => setScrollTarget(end.isIntersecting ? void 0 : end.target),
{ root: global2.document.querySelector("#panel-tab-content") }
);
if (endRef.current) {
observer.observe(endRef.current);
}
}
return () => observer?.disconnect();
}, []);
const lastStoryId = useRef7(void 0);
const lastRenderId = useRef7(0);
const emit = useChannel2(
{
[EVENTS.CALL]: setCall,
[EVENTS.SYNC]: (payload) => {
log.current = [getInternalRenderLogItem("done" /* DONE */), ...payload.logItems];
set(
(state2) => getPanelState(
{ ...state2, controlStates: payload.controlStates, pausedAt: payload.pausedAt },
{ log: log.current, calls: calls.current, collapsed, setCollapsed }
)
);
},
[STORY_RENDER_PHASE_CHANGED]: (event) => {
if (lastStoryId.current === event.storyId && ["preparing", "loading"].includes(event.newPhase)) {
return;
}
lastStoryId.current = event.storyId;
lastRenderId.current = Math.max(lastRenderId.current, event.renderId || 0);
if (lastRenderId.current !== event.renderId) {
return;
}
if (event.newPhase === "rendering") {
log.current = [getInternalRenderLogItem("active" /* ACTIVE */)];
calls.current.set(INTERNAL_RENDER_CALL_ID, getInternalRenderCall(storyId));
set({
status: "rendering",
controlStates: INITIAL_CONTROL_STATES,
pausedAt: void 0,
interactions: [],
interactionsCount: 0,
hasException: false,
caughtException: void 0,
unhandledErrors: void 0
});
} else {
set((state2) => {
const status2 = event.newPhase in playStatusMap && !terminalStatuses.includes(state2.status) ? playStatusMap[event.newPhase] : state2.status;
return getPanelState(
{ ...state2, status: status2, pausedAt: void 0 },
{ log: log.current, calls: calls.current, collapsed, setCollapsed }
);
});
}
},
[STORY_THREW_EXCEPTION]: (e2) => {
log.current = [getInternalRenderLogItem("error" /* ERROR */)];
calls.current.set(
INTERNAL_RENDER_CALL_ID,
getInternalRenderCall(storyId, { ...e2, callId: INTERNAL_RENDER_CALL_ID })
);
set(
(state2) => getPanelState(
{
...state2,
hasException: true,
caughtException: void 0,
controlStates: INITIAL_CONTROL_STATES,
pausedAt: void 0
},
{ log: log.current, calls: calls.current, collapsed, setCollapsed }
)
);
},
[PLAY_FUNCTION_THREW_EXCEPTION]: (caughtException2) => {
set((state2) => ({ ...state2, caughtException: caughtException2, hasException: true }));
},
[UNHANDLED_ERRORS_WHILE_PLAYING]: (unhandledErrors2) => {
set((state2) => ({ ...state2, unhandledErrors: unhandledErrors2, hasException: true }));
}
},
[collapsed]
);
useEffect18(() => {
set(
(state2) => getPanelState(state2, { log: log.current, calls: calls.current, collapsed, setCollapsed })
);
}, [set, collapsed]);
const controls = useMemo5(
() => ({
start: /* @__PURE__ */ __name(() => emit(EVENTS.START, { storyId }), "start"),
back: /* @__PURE__ */ __name(() => emit(EVENTS.BACK, { storyId }), "back"),
goto: /* @__PURE__ */ __name((callId) => emit(EVENTS.GOTO, { storyId, callId }), "goto"),
next: /* @__PURE__ */ __name(() => emit(EVENTS.NEXT, { storyId }), "next"),
end: /* @__PURE__ */ __name(() => emit(EVENTS.END, { storyId }), "end"),
rerun: /* @__PURE__ */ __name(() => {
emit(FORCE_REMOUNT, { storyId });
}, "rerun")
}),
[emit, storyId]
);
const storyFilePath = useParameter2("fileName", "");
const [fileName] = storyFilePath.toString().split("/").slice(-1);
const scrollToTarget = /* @__PURE__ */ __name(() => scrollTarget?.scrollIntoView({ behavior: "smooth", block: "end" }), "scrollToTarget");
const hasException = !!caughtException || !!unhandledErrors || interactions.some((v2) => v2.status === "error" /* ERROR */);
const browserTestStatus = useMemo5(() => {
if (status !== "playing" && (interactions.length > 0 || hasException)) {
return hasException ? "error" /* ERROR */ : "done" /* DONE */;
}
return status === "playing" ? "active" /* ACTIVE */ : void 0;
}, [status, interactions, hasException]);
useEffect18(() => {
const isMismatch = browserTestStatus && statusValue && statusValue !== "status-value:pending" && statusValue !== storyStatusMap[browserTestStatus];
if (isMismatch) {
const timeout = setTimeout(
() => setResultMismatch((currentValue) => {
if (!currentValue) {
emit(STORYBOOK_ADDON_TEST_CHANNEL, {
type: "test-discrepancy",
payload: {
browserStatus: browserTestStatus === "done" /* DONE */ ? "PASS" : "FAIL",
cliStatus: browserTestStatus === "done" /* DONE */ ? "FAIL" : "PASS",
storyId,
testRunId
}
});
}
return true;
}),
2e3
);
return () => clearTimeout(timeout);
} else {
setResultMismatch(false);
}
}, [emit, browserTestStatus, statusValue, storyId, testRunId]);
return React67.createElement(Fragment3, { key: "component-tests" }, React67.createElement(
InteractionsPanel,
{
storyUrl,
status,
hasResultMismatch,
browserTestStatus,
calls: calls.current,
controls,
controlStates: { ...controlStates, detached: !!refId || controlStates.detached },
interactions,
fileName,
hasException,
caughtException,
unhandledErrors,
pausedAt,
endRef,
onScrollToEnd: scrollTarget && scrollToTarget,
importPath,
canOpenInEditor,
api
}
));
}, "PanelMemoized")
);
// src/component-testing/components/PanelTitle.tsx
import React68 from "react";
import { Badge as Badge3 } from "storybook/internal/components";
import { useAddonState as useAddonState3, useStorybookApi as useStorybookApi7 } from "storybook/manager-api";
function PanelTitle() {
const api = useStorybookApi7();
const selectedPanel = api.getSelectedPanel();
const [addonState = {}] = useAddonState3(ADDON_ID7);
const { status, hasException, interactionsCount } = addonState;
return React68.createElement("div", { style: { display: "flex", alignItems: "center", gap: 6 } }, React68.createElement("span", null, "Interactions"), interactionsCount && status !== "errored" && !hasException ? React68.createElement(Badge3, { compact: true, status: selectedPanel === PANEL_ID2 ? "active" : "neutral" }, interactionsCount) : null, status === "errored" || hasException ? React68.createElement(StatusIcon, { status: "error" /* ERROR */ }) : null);
}
__name(PanelTitle, "PanelTitle");
// src/component-testing/manager.tsx
var manager_default3 = addons3.register(ADDON_ID7, () => {
if (globalThis?.FEATURES?.interactions) {
const filter = /* @__PURE__ */ __name(({ state }) => {
const origin = state.refId && state.refs[state.refId]?.url || document.location.origin;
const { pathname, search = "" } = state.location;
const path = pathname + (state.refId ? search.replace(`/${state.refId}_`, "/") : search);
return {
refId: state.refId,
storyId: state.storyId,
storyUrl: origin + path
};
}, "filter");
addons3.add(PANEL_ID2, {
type: types3.PANEL,
title: /* @__PURE__ */ __name(() => React69.createElement(PanelTitle, null), "title"),
match: /* @__PURE__ */ __name(({ viewMode }) => viewMode === "story", "match"),
render: /* @__PURE__ */ __name(({ active }) => {
return React69.createElement(AddonPanel2, { active: !!active }, React69.createElement(Consumer, { filter }, (props) => React69.createElement(Panel, { ...props })));
}, "render")
});
}
});
// src/backgrounds/manager.tsx
import React71 from "react";
import { addons as addons4, types as types4 } from "storybook/manager-api";
// src/backgrounds/components/Tool.tsx
import React70, { Fragment as Fragment4, memo as memo5, useCallback as useCallback8, useState as useState24 } from "react";
import { IconButton as IconButton7, TooltipLinkList, WithTooltip as WithTooltip5 } from "storybook/internal/components";
import { CircleIcon as CircleIcon2, GridIcon, PhotoIcon, RefreshIcon } from "@storybook/icons";
import { useGlobals as useGlobals2, useParameter as useParameter3 } from "storybook/manager-api";
var BackgroundTool = memo5(/* @__PURE__ */ __name(function BackgroundSelector() {
const config = useParameter3(PARAM_KEY3);
const [globals, updateGlobals, storyGlobals] = useGlobals2();
const [isTooltipVisible, setIsTooltipVisible] = useState24(false);
const { options = DEFAULT_BACKGROUNDS, disable = true } = config || {};
if (disable) {
return null;
}
const data = globals[PARAM_KEY3] || {};
const backgroundName = data.value;
const isGridActive = data.grid || false;
const item = options[backgroundName];
const isLocked = !!storyGlobals?.[PARAM_KEY3];
const length2 = Object.keys(options).length;
return React70.createElement(
Pure,
{
...{
length: length2,
backgroundMap: options,
item,
updateGlobals,
backgroundName,
setIsTooltipVisible,
isLocked,
isGridActive,
isTooltipVisible
}
}
);
}, "BackgroundSelector"));
var Pure = memo5(/* @__PURE__ */ __name(function PureTool(props) {
const {
item,
length: length2,
updateGlobals,
setIsTooltipVisible,
backgroundMap,
backgroundName,
isLocked,
isGridActive: isGrid,
isTooltipVisible
} = props;
const update = useCallback8(
(input) => {
updateGlobals({
[PARAM_KEY3]: input
});
},
[updateGlobals]
);
return React70.createElement(Fragment4, null, React70.createElement(
IconButton7,
{
key: "grid",
active: isGrid,
disabled: isLocked,
title: "Apply a grid to the preview",
onClick: () => update({ value: backgroundName, grid: !isGrid })
},
React70.createElement(GridIcon, null)
), length2 > 0 ? React70.createElement(
WithTooltip5,
{
key: "background",
placement: "top",
closeOnOutsideClick: true,
tooltip: ({ onHide }) => {
return React70.createElement(
TooltipLinkList,
{
links: [
...item ? [
{
id: "reset",
title: "Reset background",
icon: React70.createElement(RefreshIcon, null),
onClick: /* @__PURE__ */ __name(() => {
update(void 0);
onHide();
}, "onClick")
}
] : [],
...Object.entries(backgroundMap).map(([k2, value2]) => ({
id: k2,
title: value2.name,
icon: React70.createElement(CircleIcon2, { color: value2?.value || "grey" }),
active: k2 === backgroundName,
onClick: /* @__PURE__ */ __name(() => {
update({ value: k2, grid: isGrid });
onHide();
}, "onClick")
}))
].flat()
}
);
},
onVisibleChange: setIsTooltipVisible
},
React70.createElement(
IconButton7,
{
disabled: isLocked,
key: "background",
title: "Change the background of the preview",
active: !!item || isTooltipVisible
},
React70.createElement(PhotoIcon, null)
)
) : null);
}, "PureTool"));
// src/backgrounds/manager.tsx
var manager_default4 = addons4.register(ADDON_ID3, () => {
if (globalThis?.FEATURES?.backgrounds) {
addons4.add(ADDON_ID3, {
title: "Backgrounds",
type: types4.TOOL,
match: /* @__PURE__ */ __name(({ viewMode, tabId }) => !!(viewMode && viewMode.match(/^(story|docs)$/)) && !tabId, "match"),
render: /* @__PURE__ */ __name(() => React71.createElement(BackgroundTool, null), "render")
});
}
});
// src/measure/manager.tsx
import React74 from "react";
import { addons as addons5, types as types5 } from "storybook/manager-api";
// src/measure/Tool.tsx
import React73, { useCallback as useCallback9, useEffect as useEffect19 } from "react";
import { IconButton as IconButton8 } from "storybook/internal/components";
import { RulerIcon } from "@storybook/icons";
import { useGlobals as useGlobals3, useStorybookApi as useStorybookApi8 } from "storybook/manager-api";
var Tool = /* @__PURE__ */ __name(() => {
const [globals, updateGlobals] = useGlobals3();
const { measureEnabled } = globals || {};
const api = useStorybookApi8();
const toggleMeasure = useCallback9(
() => updateGlobals({
measureEnabled: !measureEnabled
}),
[updateGlobals, measureEnabled]
);
useEffect19(() => {
api.setAddonShortcut(ADDON_ID4, {
label: "Toggle Measure",
defaultShortcut: ["M"],
actionName: "measure",
showInMenu: false,
action: toggleMeasure
});
}, [toggleMeasure, api]);
return React73.createElement(
IconButton8,
{
key: TOOL_ID2,
active: measureEnabled,
title: "Enable measure",
onClick: toggleMeasure
},
React73.createElement(RulerIcon, null)
);
}, "Tool");
// src/measure/manager.tsx
var manager_default5 = addons5.register(ADDON_ID4, () => {
if (globalThis?.FEATURES?.measure) {
addons5.add(TOOL_ID2, {
type: types5.TOOL,
title: "Measure",
match: /* @__PURE__ */ __name(({ viewMode, tabId }) => viewMode === "story" && !tabId, "match"),
render: /* @__PURE__ */ __name(() => React74.createElement(Tool, null), "render")
});
}
});
// src/outline/manager.tsx
import React76 from "react";
import { addons as addons6, types as types6 } from "storybook/manager-api";
// src/outline/OutlineSelector.tsx
import React75, { memo as memo6, useCallback as useCallback10, useEffect as useEffect20 } from "react";
import { IconButton as IconButton9 } from "storybook/internal/components";
import { OutlineIcon } from "@storybook/icons";
import { useGlobals as useGlobals4, useStorybookApi as useStorybookApi9 } from "storybook/manager-api";
var OutlineSelector = memo6(/* @__PURE__ */ __name(function OutlineSelector2() {
const [globals, updateGlobals] = useGlobals4();
const api = useStorybookApi9();
const isActive = [true, "true"].includes(globals[PARAM_KEY4]);
const toggleOutline = useCallback10(
() => updateGlobals({
[PARAM_KEY4]: !isActive
}),
[isActive]
);
useEffect20(() => {
api.setAddonShortcut(ADDON_ID5, {
label: "Toggle Outline",
defaultShortcut: ["alt", "O"],
actionName: "outline",
showInMenu: false,
action: toggleOutline
});
}, [toggleOutline, api]);
return React75.createElement(
IconButton9,
{
key: "outline",
active: isActive,
title: "Apply outlines to the preview",
onClick: toggleOutline
},
React75.createElement(OutlineIcon, null)
);
}, "OutlineSelector"));
// src/outline/manager.tsx
var manager_default6 = addons6.register(ADDON_ID5, () => {
if (globalThis?.FEATURES?.outline) {
addons6.add(ADDON_ID5, {
title: "Outline",
type: types6.TOOL,
match: /* @__PURE__ */ __name(({ viewMode, tabId }) => !!(viewMode && viewMode.match(/^(story|docs)$/)) && !tabId, "match"),
render: /* @__PURE__ */ __name(() => React76.createElement(OutlineSelector, null), "render")
});
}
});
// src/viewport/manager.tsx
import * as React79 from "react";
import { addons as addons7, types as types7 } from "storybook/manager-api";
// src/viewport/components/Tool.tsx
import React78, { Fragment as Fragment6, useCallback as useCallback11, useEffect as useEffect21, useState as useState25 } from "react";
import { IconButton as IconButton11, TooltipLinkList as TooltipLinkList2, WithTooltip as WithTooltip6 } from "storybook/internal/components";
import { GrowIcon, RefreshIcon as RefreshIcon2, TransferIcon } from "@storybook/icons";
import { useGlobals as useGlobals5, useParameter as useParameter4 } from "storybook/manager-api";
import { Global } from "storybook/theming";
// src/viewport/shortcuts.ts
var getCurrentViewportIndex = /* @__PURE__ */ __name((viewportsKeys, current) => viewportsKeys.indexOf(current), "getCurrentViewportIndex");
var getNextViewport = /* @__PURE__ */ __name((viewportsKeys, current) => {
const currentViewportIndex = getCurrentViewportIndex(viewportsKeys, current);
return currentViewportIndex === viewportsKeys.length - 1 ? viewportsKeys[0] : viewportsKeys[currentViewportIndex + 1];
}, "getNextViewport");
var getPreviousViewport = /* @__PURE__ */ __name((viewportsKeys, current) => {
const currentViewportIndex = getCurrentViewportIndex(viewportsKeys, current);
return currentViewportIndex < 1 ? viewportsKeys[viewportsKeys.length - 1] : viewportsKeys[currentViewportIndex - 1];
}, "getPreviousViewport");
var registerShortcuts = /* @__PURE__ */ __name(async (api, viewport, updateGlobals, viewportsKeys) => {
await api.setAddonShortcut(ADDON_ID2, {
label: "Previous viewport",
defaultShortcut: ["alt", "shift", "V"],
actionName: "previous",
action: /* @__PURE__ */ __name(() => {
updateGlobals({
viewport: getPreviousViewport(viewportsKeys, viewport)
});
}, "action")
});
await api.setAddonShortcut(ADDON_ID2, {
label: "Next viewport",
defaultShortcut: ["alt", "V"],
actionName: "next",
action: /* @__PURE__ */ __name(() => {
updateGlobals({
viewport: getNextViewport(viewportsKeys, viewport)
});
}, "action")
});
await api.setAddonShortcut(ADDON_ID2, {
label: "Reset viewport",
defaultShortcut: ["alt", "control", "V"],
actionName: "reset",
action: /* @__PURE__ */ __name(() => {
updateGlobals({
viewport: { value: void 0, isRotated: false }
});
}, "action")
});
}, "registerShortcuts");
// src/viewport/utils.tsx
import React77, { Fragment as Fragment5 } from "react";
import { IconButton as IconButton10 } from "storybook/internal/components";
import { BrowserIcon, MobileIcon, TabletIcon } from "@storybook/icons";
import { styled as styled42 } from "storybook/theming";
var ActiveViewportSize = styled42.div({
display: "inline-flex",
alignItems: "center"
});
var ActiveViewportLabel = styled42.div(({ theme: theme3 }) => ({
display: "inline-block",
textDecoration: "none",
padding: 10,
fontWeight: theme3.typography.weight.bold,
fontSize: theme3.typography.size.s2 - 1,
lineHeight: "1",
height: 40,
border: "none",
borderTop: "3px solid transparent",
borderBottom: "3px solid transparent",
background: "transparent"
}));
var IconButtonWithLabel = styled42(IconButton10)(() => ({
display: "inline-flex",
alignItems: "center"
}));
var IconButtonLabel = styled42.div(({ theme: theme3 }) => ({
fontSize: theme3.typography.size.s2 - 1,
marginLeft: 10
}));
var iconsMap = {
desktop: React77.createElement(BrowserIcon, null),
mobile: React77.createElement(MobileIcon, null),
tablet: React77.createElement(TabletIcon, null),
other: React77.createElement(Fragment5, null)
};
// src/viewport/components/Tool.tsx
var ViewportTool = /* @__PURE__ */ __name(({ api }) => {
const config = useParameter4(PARAM_KEY2);
const [globals, updateGlobals, storyGlobals] = useGlobals5();
const [isTooltipVisible, setIsTooltipVisible] = useState25(false);
const { options = MINIMAL_VIEWPORTS, disable } = config || {};
const data = globals?.[PARAM_KEY2] || {};
const viewportName = typeof data === "string" ? data : data.value;
const isRotated = typeof data === "string" ? false : !!data.isRotated;
const item = options[viewportName] || responsiveViewport;
const isActive = isTooltipVisible || item !== responsiveViewport;
const isLocked = PARAM_KEY2 in storyGlobals;
const length2 = Object.keys(options).length;
useEffect21(() => {
registerShortcuts(api, viewportName, updateGlobals, Object.keys(options));
}, [options, viewportName, updateGlobals, api]);
if (item.styles === null || !options || length2 < 1) {
return null;
}
if (typeof item.styles === "function") {
console.warn(
"Addon Viewport no longer supports dynamic styles using a function, use css calc() instead"
);
return null;
}
const width = isRotated ? item.styles.height : item.styles.width;
const height = isRotated ? item.styles.width : item.styles.height;
if (disable) {
return null;
}
return React78.createElement(
Pure2,
{
...{
item,
updateGlobals,
viewportMap: options,
viewportName,
isRotated,
setIsTooltipVisible,
isLocked,
isActive,
width,
height
}
}
);
}, "ViewportTool");
var Pure2 = React78.memo(/* @__PURE__ */ __name(function PureTool2(props) {
const {
item,
viewportMap,
viewportName,
isRotated,
updateGlobals,
setIsTooltipVisible,
isLocked,
isActive,
width,
height
} = props;
const update = useCallback11(
(input) => updateGlobals({ [PARAM_KEY2]: input }),
[updateGlobals]
);
return React78.createElement(Fragment6, null, React78.createElement(
WithTooltip6,
{
placement: "bottom",
tooltip: ({ onHide }) => React78.createElement(
TooltipLinkList2,
{
links: [
...length > 0 && item !== responsiveViewport ? [
{
id: "reset",
title: "Reset viewport",
icon: React78.createElement(RefreshIcon2, null),
onClick: /* @__PURE__ */ __name(() => {
update(void 0);
onHide();
}, "onClick")
}
] : [],
...Object.entries(viewportMap).map(([k2, value2]) => ({
id: k2,
title: value2.name,
icon: iconsMap[value2.type],
active: k2 === viewportName,
onClick: /* @__PURE__ */ __name(() => {
update({ value: k2, isRotated: false });
onHide();
}, "onClick")
}))
].flat()
}
),
closeOnOutsideClick: true,
onVisibleChange: setIsTooltipVisible
},
React78.createElement(
IconButtonWithLabel,
{
disabled: isLocked,
key: "viewport",
title: "Change the size of the preview",
active: isActive,
onDoubleClick: () => {
update({ value: void 0, isRotated: false });
}
},
React78.createElement(GrowIcon, null),
item !== responsiveViewport ? React78.createElement(IconButtonLabel, null, item.name, " ", isRotated ? `(L)` : `(P)`) : null
)
), React78.createElement(
Global,
{
styles: {
[`iframe[data-is-storybook="true"]`]: { width, height }
}
}
), item !== responsiveViewport ? React78.createElement(ActiveViewportSize, null, React78.createElement(ActiveViewportLabel, { title: "Viewport width" }, width.replace("px", "")), !isLocked ? React78.createElement(
IconButton11,
{
key: "viewport-rotate",
title: "Rotate viewport",
onClick: () => {
update({ value: viewportName, isRotated: !isRotated });
}
},
React78.createElement(TransferIcon, null)
) : "/", React78.createElement(ActiveViewportLabel, { title: "Viewport height" }, height.replace("px", ""))) : null);
}, "PureTool"));
// src/viewport/manager.tsx
var manager_default7 = addons7.register(ADDON_ID2, (api) => {
if (globalThis?.FEATURES?.viewport) {
addons7.add(TOOL_ID, {
title: "viewport / media-queries",
type: types7.TOOL,
match: /* @__PURE__ */ __name(({ viewMode, tabId }) => viewMode === "story" && !tabId, "match"),
render: /* @__PURE__ */ __name(() => React79.createElement(ViewportTool, { api }), "render")
});
}
});
// src/core-server/presets/common-manager.ts
var TAG_FILTERS = "tag-filters";
var STATIC_FILTER = "static-filter";
var tagFiltersManager = addons8.register(TAG_FILTERS, (api) => {
const staticExcludeTags = Object.entries(global3.TAGS_OPTIONS ?? {}).reduce(
(acc, entry) => {
const [tag, option] = entry;
if (option.excludeFromSidebar) {
acc[tag] = true;
}
return acc;
},
{}
);
api.experimental_setFilter(STATIC_FILTER, (item) => {
const tags = item.tags ?? [];
return (
// we can filter out the primary story, but we still want to show autodocs
(tags.includes("dev") || item.type === "docs") && tags.filter((tag) => staticExcludeTags[tag]).length === 0
);
});
});
var common_manager_default = [
manager_default5,
tagFiltersManager,
manager_default2,
manager_default4,
manager_default3,
manager_default,
manager_default7,
manager_default6
];
export {
common_manager_default as default
};