UNPKG

storybook-addon-test-codegen

Version:

Addon for Storybook that generates test code for your stories.

5 lines 26.4 kB
import i,{useEffect,useMemo,useRef,useState,useLayoutEffect,useCallback}from'react';import {addons,types,useChannel,useStorybookApi,useAddonState,useGlobals,experimental_requestResponse}from'storybook/internal/manager-api';import {IconButton,Button,Form,AddonPanel,Bar,EmptyTabContent,Spaced,Badge,WithTooltip,TooltipNote,SyntaxHighlighter}from'storybook/internal/components';import {AlertIcon,CheckIcon,SyncIcon,CrossIcon,AddIcon,DeleteIcon,CopyIcon}from'@storybook/icons';import {styled}from'storybook/internal/theming';function te(t,e,n){var o=this,c=useRef(null),r=useRef(0),s=useRef(null),l=useRef([]),u=useRef(),a=useRef(),m=useRef(t),f=useRef(!0);m.current=t;var p=typeof window<"u",v=!e&&e!==0&&p;if(typeof t!="function")throw new TypeError("Expected a function");e=+e||0;var d=!!(n=n||{}).leading,b=!("trailing"in n)||!!n.trailing,w="maxWait"in n,x="debounceOnServer"in n&&!!n.debounceOnServer,C=w?Math.max(+n.maxWait||0,e):null;useEffect(function(){return f.current=!0,function(){f.current=!1;}},[]);var S=useMemo(function(){var T=function(E){var I=l.current,G=u.current;return l.current=u.current=null,r.current=E,a.current=m.current.apply(G,I)},P=function(E,I){v&&cancelAnimationFrame(s.current),s.current=v?requestAnimationFrame(E):setTimeout(E,I);},H=function(E){if(!f.current)return !1;var I=E-c.current;return !c.current||I>=e||I<0||w&&E-r.current>=C},nt=function(E){return s.current=null,b&&l.current?T(E):(l.current=u.current=null,a.current)},U=function E(){var I=Date.now();if(H(I))return nt(I);if(f.current){var G=e-(I-c.current),qt=w?Math.min(G,C-(I-r.current)):G;P(E,qt);}},M=function(){if(p||x){var E=Date.now(),I=H(E);if(l.current=[].slice.call(arguments),u.current=o,c.current=E,I){if(!s.current&&f.current)return r.current=c.current,P(U,e),d?T(c.current):a.current;if(w)return P(U,e),T(c.current)}return s.current||P(U,e),a.current}};return M.cancel=function(){s.current&&(v?cancelAnimationFrame(s.current):clearTimeout(s.current)),r.current=0,l.current=c.current=u.current=s.current=null;},M.isPending=function(){return !!s.current},M.flush=function(){return s.current?nt(Date.now()):a.current},M},[d,w,e,C,b,v,p,x]);return S}function ee(t,e){return t===e}function ot(t,e,n){var o=ee,c=useRef(t),r=useState({})[1],s=te(useCallback(function(u){c.current=u,r({});},[r]),e,n),l=useRef(t);return o(l.current,t)||(s(t),l.current=t),[c.current,s]}function A(t){"@babel/helpers - typeof";return A=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},A(t)}function ct(t,e){if(A(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var o=n.call(t,e||"default");if(A(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function it(t){var e=ct(t,"string");return A(e)=="symbol"?e:e+""}function st(t,e,n){return (e=it(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function F(){return F=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var o in n)({}).hasOwnProperty.call(n,o)&&(t[o]=n[o]);}return t},F.apply(null,arguments)}function rt(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(c){return Object.getOwnPropertyDescriptor(t,c).enumerable})),n.push.apply(n,o);}return n}function $(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?rt(Object(n),!0).forEach(function(o){st(t,o,n[o]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):rt(Object(n)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(n,o));});}return t}function oe(t){var e=t.length;if(e===0||e===1)return t;if(e===2)return [t[0],t[1],"".concat(t[0],".").concat(t[1]),"".concat(t[1],".").concat(t[0])];if(e===3)return [t[0],t[1],t[2],"".concat(t[0],".").concat(t[1]),"".concat(t[0],".").concat(t[2]),"".concat(t[1],".").concat(t[0]),"".concat(t[1],".").concat(t[2]),"".concat(t[2],".").concat(t[0]),"".concat(t[2],".").concat(t[1]),"".concat(t[0],".").concat(t[1],".").concat(t[2]),"".concat(t[0],".").concat(t[2],".").concat(t[1]),"".concat(t[1],".").concat(t[0],".").concat(t[2]),"".concat(t[1],".").concat(t[2],".").concat(t[0]),"".concat(t[2],".").concat(t[0],".").concat(t[1]),"".concat(t[2],".").concat(t[1],".").concat(t[0])];if(e>=4)return [t[0],t[1],t[2],t[3],"".concat(t[0],".").concat(t[1]),"".concat(t[0],".").concat(t[2]),"".concat(t[0],".").concat(t[3]),"".concat(t[1],".").concat(t[0]),"".concat(t[1],".").concat(t[2]),"".concat(t[1],".").concat(t[3]),"".concat(t[2],".").concat(t[0]),"".concat(t[2],".").concat(t[1]),"".concat(t[2],".").concat(t[3]),"".concat(t[3],".").concat(t[0]),"".concat(t[3],".").concat(t[1]),"".concat(t[3],".").concat(t[2]),"".concat(t[0],".").concat(t[1],".").concat(t[2]),"".concat(t[0],".").concat(t[1],".").concat(t[3]),"".concat(t[0],".").concat(t[2],".").concat(t[1]),"".concat(t[0],".").concat(t[2],".").concat(t[3]),"".concat(t[0],".").concat(t[3],".").concat(t[1]),"".concat(t[0],".").concat(t[3],".").concat(t[2]),"".concat(t[1],".").concat(t[0],".").concat(t[2]),"".concat(t[1],".").concat(t[0],".").concat(t[3]),"".concat(t[1],".").concat(t[2],".").concat(t[0]),"".concat(t[1],".").concat(t[2],".").concat(t[3]),"".concat(t[1],".").concat(t[3],".").concat(t[0]),"".concat(t[1],".").concat(t[3],".").concat(t[2]),"".concat(t[2],".").concat(t[0],".").concat(t[1]),"".concat(t[2],".").concat(t[0],".").concat(t[3]),"".concat(t[2],".").concat(t[1],".").concat(t[0]),"".concat(t[2],".").concat(t[1],".").concat(t[3]),"".concat(t[2],".").concat(t[3],".").concat(t[0]),"".concat(t[2],".").concat(t[3],".").concat(t[1]),"".concat(t[3],".").concat(t[0],".").concat(t[1]),"".concat(t[3],".").concat(t[0],".").concat(t[2]),"".concat(t[3],".").concat(t[1],".").concat(t[0]),"".concat(t[3],".").concat(t[1],".").concat(t[2]),"".concat(t[3],".").concat(t[2],".").concat(t[0]),"".concat(t[3],".").concat(t[2],".").concat(t[1]),"".concat(t[0],".").concat(t[1],".").concat(t[2],".").concat(t[3]),"".concat(t[0],".").concat(t[1],".").concat(t[3],".").concat(t[2]),"".concat(t[0],".").concat(t[2],".").concat(t[1],".").concat(t[3]),"".concat(t[0],".").concat(t[2],".").concat(t[3],".").concat(t[1]),"".concat(t[0],".").concat(t[3],".").concat(t[1],".").concat(t[2]),"".concat(t[0],".").concat(t[3],".").concat(t[2],".").concat(t[1]),"".concat(t[1],".").concat(t[0],".").concat(t[2],".").concat(t[3]),"".concat(t[1],".").concat(t[0],".").concat(t[3],".").concat(t[2]),"".concat(t[1],".").concat(t[2],".").concat(t[0],".").concat(t[3]),"".concat(t[1],".").concat(t[2],".").concat(t[3],".").concat(t[0]),"".concat(t[1],".").concat(t[3],".").concat(t[0],".").concat(t[2]),"".concat(t[1],".").concat(t[3],".").concat(t[2],".").concat(t[0]),"".concat(t[2],".").concat(t[0],".").concat(t[1],".").concat(t[3]),"".concat(t[2],".").concat(t[0],".").concat(t[3],".").concat(t[1]),"".concat(t[2],".").concat(t[1],".").concat(t[0],".").concat(t[3]),"".concat(t[2],".").concat(t[1],".").concat(t[3],".").concat(t[0]),"".concat(t[2],".").concat(t[3],".").concat(t[0],".").concat(t[1]),"".concat(t[2],".").concat(t[3],".").concat(t[1],".").concat(t[0]),"".concat(t[3],".").concat(t[0],".").concat(t[1],".").concat(t[2]),"".concat(t[3],".").concat(t[0],".").concat(t[2],".").concat(t[1]),"".concat(t[3],".").concat(t[1],".").concat(t[0],".").concat(t[2]),"".concat(t[3],".").concat(t[1],".").concat(t[2],".").concat(t[0]),"".concat(t[3],".").concat(t[2],".").concat(t[0],".").concat(t[1]),"".concat(t[3],".").concat(t[2],".").concat(t[1],".").concat(t[0])]}var q={};function ce(t){if(t.length===0||t.length===1)return t;var e=t.join(".");return q[e]||(q[e]=oe(t)),q[e]}function ie(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,o=t.filter(function(r){return r!=="token"}),c=ce(o);return c.reduce(function(r,s){return $($({},r),n[s])},e)}function at(t){return t.join(" ")}function se(t,e){var n=0;return function(o){return n+=1,o.map(function(c,r){return W({node:c,stylesheet:t,useInlineStyles:e,key:"code-segment-".concat(n,"-").concat(r)})})}}function W(t){var e=t.node,n=t.stylesheet,o=t.style,c=o===void 0?{}:o,r=t.useInlineStyles,s=t.key,l=e.properties,u=e.type,a=e.tagName,m=e.value;if(u==="text")return m;if(a){var f=se(n,r),p;if(!r)p=$($({},l),{},{className:at(l.className)});else {var v=Object.keys(n).reduce(function(x,C){return C.split(".").forEach(function(S){x.includes(S)||x.push(S);}),x},[]),d=l.className&&l.className.includes("token")?["token"]:[],b=l.className&&d.concat(l.className.filter(function(x){return !v.includes(x)}));p=$($({},l),{},{className:at(b)||void 0,style:ie(l.className,Object.assign({},l.style,c),n)});}var w=f(e.children);return i.createElement(a,F({key:s},p),w)}}var de=styled.div(({theme:t})=>({display:"flex",flexDirection:"column",border:`1px solid ${t.appBorderColor}`})),fe=styled.div(({theme:t,isSticky:e})=>({fontSize:t.typography.size.s1,fontWeight:"bold",marginBottom:4,padding:"6px 7px",background:t.barBg,borderBottom:`1px solid ${t.appBorderColor}`,position:"relative",...e?{position:"sticky",top:0,zIndex:1}:{}})),ye=styled.div({padding:"6px 7px 10px",height:"100%",tabSize:"8px",pre:{margin:0,borderRadius:0}}),me=styled.div({position:"absolute",top:"50%",transform:"translateY(-50%)",right:0,zIndex:1}),ge=styled(IconButton)(({theme:t})=>({padding:0,width:20,height:20,marginRight:4})),ve=styled(AlertIcon)(({theme:t})=>({color:t.color.warning,width:12,height:12}));function J({name:t,codeLines:e,isSticky:n}){let[o,c]=useState(!1),[r,s]=useState(null),l=e.flatMap(a=>a.text.split(` `).map((m,f)=>({text:m,warning:a.warning&&f===0?a.warning:void 0}))),u=l.map(({text:a})=>a).join(` `);return i.createElement(de,null,i.createElement(fe,{isSticky:n},t,i.createElement(me,null,i.createElement(WithTooltip,{placement:"top",as:"div",hasChrome:!1,trigger:"hover",tooltip:i.createElement(TooltipNote,{note:"Copy"})},i.createElement(IconButton,{onClick:()=>navigator.clipboard.writeText(u).then(()=>{c(!0),r&&clearTimeout(r),s(setTimeout(()=>{c(!1),s(null);},2e3));})},o?i.createElement(CheckIcon,{size:16}):i.createElement(CopyIcon,{size:16}))))),i.createElement(ye,null,i.createElement(SyntaxHighlighter,{language:"typescript",renderer:({rows:a,useInlineStyles:m})=>a.map((f,p)=>{let v=l[p]?.warning;if(v){let d={type:"element",tagName:Ee,properties:{className:[],warning:v},children:[]};f.children.splice(0,1,d);}else p>0&&p<a.length-1&&f.children[0].properties&&(f.children[0].properties.style={marginRight:"16px"});return W({node:f,stylesheet:{},useInlineStyles:m,key:`code-segement${p}`})})},u)))}var he=styled.div(({theme:t})=>({fontWeight:t.typography.weight.bold,fontSize:t.typography.size.s2,marginBottom:12})),be=styled.div(({theme:t})=>({color:t.color.defaultText})),Se=styled.div(({theme:t})=>({color:t.color.defaultText,lineHeight:"18px",padding:15,width:350})),xe={ROLE_WITHOUT_NAME:{title:"Role without name",description:i.createElement("div",null,i.createElement("div",null,i.createElement("strong",null,"getByRole")," without name can match any button, making tests unreliable."),i.createElement("div",{style:{margin:"8px 0"}},"To fix, add ",i.createElement("strong",null,"visible text")," or ",i.createElement("strong",null,"aria-label")," to your element:"),i.createElement("div",{style:{margin:"8px 0"}},i.createElement("div",null,"\u274C ",i.createElement("code",null,"<button />")),i.createElement("div",null,"\u2705 ",i.createElement("code",null,"<button>Submit</button>")),i.createElement("div",null,"\u2705 ",i.createElement("code",null,'<button aria-label="Submit">Icon</button>'))))},QUERY_SELECTOR:{title:"Query selector usage",description:i.createElement("div",null,i.createElement("div",null,i.createElement("strong",null,"querySelector")," is fragile and breaks when HTML structure changes."),i.createElement("div",{style:{margin:"8px 0"}},"To fix, use ",i.createElement("strong",null,"semantic HTML")," or ",i.createElement("strong",null,"aria-label")," ","to make the element accessible:"),i.createElement("div",{style:{margin:"8px 0"}},i.createElement("div",null,"\u274C ",i.createElement("code",null,'<div class="submit-18372">Submit</div>')),i.createElement("div",null,"\u2705 ",i.createElement("code",null,"<button>Submit</button>")),i.createElement("div",null,"\u2705 ",i.createElement("code",null,'<div aria-label="Submit">Icon</div>'))))},TEST_ID:{title:"Test ID usage",description:i.createElement("div",null,i.createElement("div",null,i.createElement("strong",null,"data-testid")," elements are not accessible and do not resemble how your software is used."),i.createElement("div",{style:{margin:"8px 0"}},"To improve, use ",i.createElement("strong",null,"semantic HTML")," or"," ",i.createElement("strong",null,"aria-label")," to make the element accessible:"),i.createElement("div",{style:{margin:"8px 0"}},i.createElement("div",null,"\u274C ",i.createElement("code",null,'<div data-testid="submit">Submit</div>')),i.createElement("div",null,"\u2705 ",i.createElement("code",null,"<button>Submit</button>"))))}};function Ee({warning:t}){let{title:e,description:n}=xe[t];return i.createElement(WithTooltip,{trigger:"hover",tooltip:i.createElement(Se,null,i.createElement(he,null,e),i.createElement(be,null,n))},i.createElement(ge,null,i.createElement(ve,null)))}var dt=Object.prototype.hasOwnProperty;function ft(t,e,n){for(n of t.keys())if(j(n,e))return n}function j(t,e){var n,o,c;if(t===e)return !0;if(t&&e&&(n=t.constructor)===e.constructor){if(n===Date)return t.getTime()===e.getTime();if(n===RegExp)return t.toString()===e.toString();if(n===Array){if((o=t.length)===e.length)for(;o--&&j(t[o],e[o]););return o===-1}if(n===Set){if(t.size!==e.size)return !1;for(o of t)if(c=o,c&&typeof c=="object"&&(c=ft(e,c),!c)||!e.has(c))return !1;return !0}if(n===Map){if(t.size!==e.size)return !1;for(o of t)if(c=o[0],c&&typeof c=="object"&&(c=ft(e,c),!c)||!j(o[1],e.get(c)))return !1;return !0}if(n===ArrayBuffer)t=new Uint8Array(t),e=new Uint8Array(e);else if(n===DataView){if((o=t.byteLength)===e.byteLength)for(;o--&&t.getInt8(o)===e.getInt8(o););return o===-1}if(ArrayBuffer.isView(t)){if((o=t.byteLength)===e.byteLength)for(;o--&&t[o]===e[o];);return o===-1}if(!n||typeof t=="object"){o=0;for(n in t)if(dt.call(t,n)&&++o&&!dt.call(e,n)||!(n in e)||!j(t[n],e[n]))return !1;return Object.keys(e).length===o}}return t!==t&&e!==e}var O="storybook/test-codegen",yt=`${O}/panel`;var X=`${O}/is-recording`,Z=`${O}/is-asserting`,_={INTERACTION:`${O}/interaction`,SAVE_NEW_STORY_REQUEST:`${O}/save-new-story-request`,SAVE_NEW_STORY_RESPONSE:`${O}/save-new-story-response`};var gt=styled.div(({theme:t})=>({height:"100%",background:t.background.content,display:"flex",flexDirection:"column"})),vt=styled.div({flex:1,overflow:"auto"}),ht=styled.div(({theme:t})=>({background:t.background.app,borderBottom:`1px solid ${t.appBorderColor}`,position:"sticky",top:0,zIndex:2})),bt=styled.nav(({theme:t})=>({height:40,display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 15px"})),B=styled(Button)(({theme:t})=>({position:"relative",borderRadius:4,padding:"6px 8px",color:t.textMutedColor,"&:not(:disabled)":{"&:hover,&:focus-visible":{color:t.color.secondary}},marginBottom:1,lineHeight:"12px"})),tt=styled.div(({isHidden:t})=>({display:"flex",alignItems:"center",gap:6,opacity:t?0:1})),St=styled(tt)({left:8,top:"50%",transform:"translateY(-50%)",position:"absolute"}),xt=styled(B)(({isAsserting:t})=>({backgroundColor:t?"rgba(0, 128, 0, 0.1)":void 0,color:t?"rgb(0, 128, 0)":void 0})),Et=styled(B)({cursor:"not-allowed"}),It=styled(Button)({color:"white"}),wt=styled.div({display:"flex",alignItems:"center",gap:"9px"}),Ct=styled.div(({theme:t})=>({display:"flex",alignItems:"center",gap:"8px"})),z=styled.span(({theme:t,isRecording:e})=>({width:14,height:14,borderRadius:"50%",backgroundColor:e?t.color.negative:t.color.secondary,display:"inline-block"})),Tt=styled.div({padding:"16px",display:"flex",flexDirection:"column",gap:"12px"}),kt=styled.form({display:"flex",alignItems:"center",gap:8}),et=styled(CheckIcon)(({theme:t})=>({width:12,color:t.color.secondary})),Ot=styled(Form.Input)(({theme:t})=>({paddingLeft:10,paddingRight:10,fontSize:t.typography.size.s1,height:28,minHeight:"unset",...t.base==="light"&&{color:t.color.darkest},"::placeholder":{color:t.color.mediumdark},"&:invalid:not(:placeholder-shown)":{boxShadow:`${t.color.negative} 0 0 0 1px inset`},"&::-webkit-search-decoration, &::-webkit-search-cancel-button, &::-webkit-search-results-button, &::-webkit-search-results-decoration":{display:"none"}})),Nt=styled(SyncIcon)(({theme:t})=>({animation:`${t.animation.rotate360} 1s linear infinite;`})),Bt=styled(CheckIcon)({width:12}),At=styled(Button)(({theme:t})=>({color:t.color.negative})),_t=styled(CrossIcon)(({theme:t})=>({color:t.color.negative})),Dt=styled(AddIcon)({width:14});var _e=t=>JSON.stringify(t,(e,n)=>typeof n=="function"?"__sb_empty_function_arg__":n),jt=({code:t,turnOffRecording:e})=>{let n=useStorybookApi(),[o,c]=useState(""),[r,s]=useState("button"),l=n.getCurrentStoryData();useEffect(()=>{c(l?.name),s("button");},[l?.name]);let u=async()=>{s("creating");let m={code:t,csfId:l.id,importPath:l.importPath,args:_e("args"in l?Object.entries(l.args||{}).reduce((p,[v,d])=>(j(d,l.initialArgs?.[v])||(p[v]=d),p),{}):{}),name:o},f=n.getChannel();if(f)try{let{newStoryId:p}=await experimental_requestResponse(f,_.SAVE_NEW_STORY_REQUEST,_.SAVE_NEW_STORY_RESPONSE,m);p===l.id?(s("success"),setTimeout(()=>{s("button");},2e3)):(s("button"),n.addNotification({id:"create-new-story-file-success",content:{headline:"Story file created",subHeadline:`${o} was created`},duration:8e3,icon:i.createElement(CheckIcon,null)})),await Lt(n.selectStory,p);}catch(p){console.error(p),n.addNotification({id:"create-new-story-file-error",content:{headline:"Failed to save story",subHeadline:"Please try again"},duration:8e3,icon:i.createElement(CheckIcon,null)}),s("error"),setTimeout(()=>{s("button");},2e3);}finally{e();}},a=global.CONFIG_TYPE==="DEVELOPMENT";return i.createElement(kt,null,r==="button"&&a&&i.createElement(B,{onClick:()=>s("input"),variant:"outline"},i.createElement(et,{size:16})," Save to story"),r==="button"&&!a&&i.createElement(WithTooltip,{as:"div",hasChrome:!1,trigger:"hover",tooltip:i.createElement(TooltipNote,{note:"Only available in development mode"})},i.createElement(Et,{variant:"outline",type:"button"},i.createElement(et,{size:16})," Save to story")),r==="input"&&i.createElement(i.Fragment,null,i.createElement(Ot,{placeholder:"Type story name",required:!0,autoFocus:!0,value:o,onChange:m=>c(m.target.value)}),i.createElement(B,{onClick:u,type:"submit",variant:"outline"},"Save")),r==="creating"&&i.createElement(B,{onClick:()=>s("input"),variant:"outline"},i.createElement(Nt,null)," Saving"),r==="success"&&i.createElement(It,{variant:"solid",type:"button"},i.createElement(Bt,null)," Saved"),r==="error"&&i.createElement(At,{variant:"ghost",type:"button"},i.createElement(_t,null)," Failed to save"))};async function Lt(t,e,n=1){if(n>10)throw new Error("We could not select the new story. Please try again.");try{await t(e);}catch{return await new Promise(c=>setTimeout(c,500)),Lt(t,e,n+1)}}var D=t=>t.map(e=>typeof e=="string"?Q(e):typeof e=="object"&&e!==null?Array.isArray(e)?`[${e.map(n=>typeof n=="string"?Q(n):n).join(", ")}]`:`{ ${Object.entries(e).reduce((n,[o,c])=>(typeof c=="object"&&c!==null?n.push(`${o}: ${D([c])}`):n.push(`${o}: ${typeof c=="string"?Q(c):c}`),n),[]).join(", ")} }`:String(e)).join(", "),Q=t=>{let e=t.replace(/\\/g,"\\\\");return e.includes(` `)?`\`${e.replace(/`/g,"\\`")}\``:`'${e.replace(/'/g,"\\'")}'`};var Wt=(t,e)=>{let n=[...e];if(t.event.type==="dblclick"){let o=0;for(let c=n.length-1;c>=0&&o<2;c--)n[c].event.type==="click"&&(n.splice(c,1),o++);return n.push(t),n}if(t.event.type==="type"){for(let o=n.length-1;o>=0;o--){let c=n[o],r=c.event.type!=="type",s=c.event.type==="keydown"&&c.event.key==="shift";if(r&&!s)return n.push(t),n;if(c?.event.type==="type"&&De(c,t))return c.event.value=t.event.value,n}return n.push(t),n}if(t.event.type==="keyup"){for(let o=n.length-1;o>=0;o--){let c=n[o];if(c.event.type==="keydown"&&c.event.key==="shift")return n.splice(o,1),n}return n}if(t.event.type==="focus"){let o=!1,c=null;for(let r=n.length-1;r>=0;r--){let s=n[r];if(s?.event.type==="keydown"&&s?.event.key==="tab"&&(c=r),s?.event.type==="keydown"&&s?.event.key==="shift"){o=!0;break}}return c!==null&&(n.splice(c,1),n.push({elementQuery:t.elementQuery,event:{type:"focus",shift:o}})),n}return n.push(t),n},De=(t,e)=>t.elementQuery.object===e.elementQuery.object&&t.elementQuery.method===e.elementQuery.method&&D(t.elementQuery.args)===D(e.elementQuery.args)&&t.elementQuery.nth===e.elementQuery.nth;var Qt={click:"click",dblclick:"dblClick",keydown:"keyboard",type:"type",select:"selectOptions",upload:"upload",focus:"focus"},Mt=(t,e)=>{let n=[],o=!1,c=!1,r=!1;for(let u of t){let{event:a}=u;if(a.type==="keyup"||a.type==="keydown"&&["shift","tab"].includes(a.key))continue;if(a.type==="assertion"){r=!0;let{queryString:b,asElementPostfix:w,warning:x}=Ht(u.elementQuery,e),C=`expect(${b.replace(w,"")})`.replace("await ","").replace("canvas.find","canvas.query");a.args&&a.args.length>0?C+=`.${a.assertionType}(${D(a.args)})`:C+=`.${a.assertionType}()`,u.elementQuery.object==="body"&&(o=!0),u.elementQuery.object==="canvas"&&(c=!0),n.push({text:`await waitFor(() => ${C})`,warning:x});continue}let m=`await userEvent.${Qt[a.type]}`,{queryString:f,assertion:p,warning:v}=Ht(u.elementQuery,e),d="";a.type==="type"?a.value===""?(m=m.replace(Qt[a.type],"clear"),d=""):d=`, ${Q(a.value)}`:a.type==="keydown"?(f="",p=null,v=void 0,d=`'${a.key}'`):a.type==="select"?d=`, [${a.options.map(b=>`'${b}'`).join(", ")}]`:a.type==="upload"?d=`, [${a.files.map(b=>`new File(['${b}'], '${b}')`).join(", ")}]`:a.type==="focus"&&(m=m.replace("focus","tab"),f="",p=null,v=void 0,d=a.shift?"{ shift: true }":""),f&&(u.elementQuery.object==="body"?o=!0:c=!0),p&&(n.push({text:p,warning:v}),r=!0),n.push({text:`${m}(${f}${d});`,warning:v});}if(!n.length)return {imports:[],play:[]};let s=["userEvent"];c&&s.push("within"),(r||o)&&s.push("waitFor","expect");let l=[{text:"play: async ({ canvasElement }) => {"}];return o&&l.push({text:V("const body = canvasElement.ownerDocument.body;")}),c&&(o?l.push({text:V("const canvas = within(body);")}):l.push({text:V("const canvas = within(canvasElement.ownerDocument.body);")})),l.push(...n.map(u=>({text:V(u.text),warning:u.warning})),{text:"}"}),{imports:[{text:`import { ${s.join(", ")} } from 'storybook/test';`}],play:l}},V=t=>` ${t}`,Ht=(t,e)=>{let n=" as HTMLElement",o=`${t.object==="canvas"?"await ":""}${t.object}.${t.method}`,c=D(t.args),r;t.method==="querySelector"?r="QUERY_SELECTOR":t.method.includes("ByRole")&&(!t.args[1]||!("name"in t.args[1]))?r="ROLE_WITHOUT_NAME":t.method.includes("ByTestId")&&(r="TEST_ID");let s=t.object==="body"&&e?n:"",l=`${o}(${c})${s}`,u=t.nth===null?l:`(${l})[${t.nth}]`,a=u.replace(s,"");return {assertion:t.object==="body"?`await waitFor(() => expect(${a}).toBeInTheDocument());`:null,queryString:u,asElementPostfix:n,warning:r}};var Y=()=>useAddonState(O,JSON.stringify([])),K=()=>{let[t,e]=useGlobals();return [t[X]===!0,n=>{e({[X]:n});}]},Ft=()=>{let[t,e]=useGlobals();return [t[Z]===!0,n=>{e({[Z]:n});}]};var Kt=()=>{let[t,e]=Y(),[n,o]=K(),[c,r]=Ft();useChannel({[_.INTERACTION]:S=>{e(T=>JSON.stringify(Wt(S,JSON.parse(T))));}});let s=()=>{n&&c&&r(!1),o(!n);},l=()=>r(!c),u=()=>e(()=>JSON.stringify([])),m=useStorybookApi().getCurrentStoryData(),f=()=>{o(!1),r(!1);};useEffect(()=>{u(),f();},[m?.id]);let p=[".ts",".tsx"].some(S=>m?.importPath.endsWith(S)),[v]=ot(t,100),d=useMemo(()=>Mt(JSON.parse(v),p),[v,p]),b=useRef(null);useEffect(()=>{b.current?.parentElement?.style&&(b.current.parentElement.style.height="100%");},[]);let w=useRef(null),[x,C]=useState(!0);return useLayoutEffect(()=>{let S=w.current;if(!S||!x)return;let T=new MutationObserver(()=>{x&&setTimeout(()=>{S.scrollTop=S.scrollHeight;});});return T.observe(S,{childList:!0,subtree:!0}),()=>T.disconnect()},[d,x]),i.createElement(gt,{ref:b},i.createElement(ht,null,i.createElement(Bar,null,i.createElement(bt,null,i.createElement(wt,null,i.createElement(B,{onClick:s},i.createElement(tt,{isHidden:n},i.createElement(z,{isRecording:!1}),"Start recording"),i.createElement(St,{isHidden:!n},i.createElement(z,{isRecording:!0}),"Stop recording")),i.createElement(xt,{disabled:!n,onClick:l,isAsserting:c},i.createElement(Dt,null),c?"Choose element":"Add assertion"),i.createElement(B,{onClick:u,disabled:!d.play.length},i.createElement(DeleteIcon,null),"Reset")),d.play.length>0&&i.createElement(jt,{code:d,turnOffRecording:f})))),i.createElement(vt,{ref:w,onScroll:S=>{let{scrollTop:T,scrollHeight:P,clientHeight:H}=S.target;C(T+H>=P);}},d.play.length===0&&!n&&i.createElement(EmptyTabContent,{title:"No interactions have been recorded.",description:i.createElement(Ct,null,"Click the record button",i.createElement(z,{isRecording:!1,onClick:s,style:{cursor:"pointer"}}),"to start recording.")}),d.play.length===0&&n&&i.createElement(EmptyTabContent,{title:"Recording is in progress...",description:c?"Click on elements to record assertions.":"Interact with the story to record events."}),d.play.length>0&&i.createElement(Tt,null,i.createElement(J,{name:"Imports",codeLines:d.imports}),i.createElement(J,{name:"Play Function",codeLines:d.play,isSticky:!0}))))};function Ye(){let[t]=Y(),[e]=K();return i.createElement("div",null,i.createElement(Spaced,{col:1},i.createElement("span",{style:{display:"inline-block",verticalAlign:"middle"}},"Interaction Recorder"),e&&i.createElement(Badge,{status:"neutral"},JSON.parse(t).length)))}addons.register(O,t=>{t.getChannel()?.on(_.SAVE_NEW_STORY_RESPONSE,n=>{if(!n.success)return;let o=t.getCurrentStoryData();o.type==="story"&&(t.resetStoryArgs(o),n.payload.newStoryId&&t.selectStory(n.payload.newStoryId));}),addons.add(yt,{type:types.PANEL,title:Ye,match:({viewMode:n})=>n==="story",render:({active:n})=>i.createElement(AddonPanel,{active:n??!1},i.createElement(Kt,null))});});//# sourceMappingURL=manager.js.map //# sourceMappingURL=manager.js.map