45 lines
23 KiB
JavaScript
45 lines
23 KiB
JavaScript
"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["7297"],{6962:function(e,t,s){s.r(t),s.d(t,{default:()=>p,frontMatter:()=>a,metadata:()=>n,assets:()=>d,toc:()=>c,contentTitle:()=>l});var n=JSON.parse('{"id":"features/tests","title":"Tests","description":"Overview","source":"@site/docs/features/tests.mdx","sourceDirName":"features","slug":"/features/tests","permalink":"/docs/features/tests","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/features/tests.mdx","tags":[],"version":"current","frontMatter":{},"sidebar":"docsSidebar","previous":{"title":"Compiled Code","permalink":"/docs/features/compiled-code"},"next":{"title":"Module Resolution","permalink":"/docs/features/module-resolution"}}'),r=s("5893"),i=s("65"),o=s("3365");let a={},l="Tests",d={},c=[{value:"Overview",id:"overview",level:2},{value:"Use Cases",id:"use-cases",level:2},{value:"Demos",id:"demos",level:2},{value:"Tests Panel",id:"tests-panel",level:2},{value:"Supported Languages",id:"supported-languages",level:2},{value:"Importing Code",id:"importing-code",level:2},{value:"Supported Jest features",id:"supported-jest-features",level:2},{value:"Supported testing libraries",id:"supported-testing-libraries",level:2},{value:"Testing library",id:"testing-library",level:3},{value:"Chai",id:"chai",level:3},{value:"Examples",id:"examples",level:2},{value:"SDK",id:"sdk",level:2}];function h(e){let t={a:"a",admonition:"admonition",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",img:"img",li:"li",p:"p",pre:"pre",ul:"ul",...(0,i.a)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(t.header,{children:(0,r.jsx)(t.h1,{id:"tests",children:"Tests"})}),"\n","\n",(0,r.jsx)(t.h2,{id:"overview",children:"Overview"}),"\n",(0,r.jsx)(t.p,{children:"Automated tests can be added for projects. The tests are run in the context of the result web page."}),"\n",(0,r.jsxs)(t.p,{children:["The automated tests are run by the ",(0,r.jsx)("a",{href:"https://jestjs.io/",target:"_blank",children:"Jest testing framework"}),", which runs totally in the browser. In addition, other ",(0,r.jsx)(t.a,{href:"#supported-testing-libraries",children:"testing libraries"})," are also supported."]}),"\n",(0,r.jsx)(t.p,{children:"Screenshots:"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.img,{alt:"Livecodes Tests",src:s(9493).Z+"",width:"2240",height:"1400"})}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.img,{alt:"Livecodes Tests",src:s(2580).Z+"",width:"2240",height:"1400"})}),"\n",(0,r.jsx)(t.h2,{id:"use-cases",children:"Use Cases"}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsx)(t.li,{children:"Automated tests increase the confidence in the code and can improve the quality of projects."}),"\n",(0,r.jsxs)(t.li,{children:["Allows ",(0,r.jsx)("a",{href:"https://en.wikipedia.org/wiki/Test-driven_development",target:"_blank",children:"Test-driven development (TDD)"}),"."]}),"\n",(0,r.jsxs)(t.li,{children:["Can be used for education and training by preparing projects with tests that are required to pass by the students' implementation (similar to ",(0,r.jsx)("a",{href:"https://www.freecodecamp.org/learn",target:"_blank",children:"freeCodeCamp"}),")."]}),"\n",(0,r.jsxs)(t.li,{children:["Can be used by wesites that offer coding challenges (similar to ",(0,r.jsx)("a",{href:"https://www.codewars.com/",target:"_blank",children:"Codewars"}),")."]}),"\n"]}),"\n",(0,r.jsx)(t.h2,{id:"demos",children:"Demos"}),"\n",(0,r.jsx)(t.p,{children:"Demo: (template=jest)"}),"\n",(0,r.jsx)(o.Z,{template:"jest",params:{tests:"open"}}),"\n",(0,r.jsx)("p",{children:"\xa0"}),"\n",(0,r.jsx)(t.p,{children:"Demo: (template=jest-react)"}),"\n",(0,r.jsx)(o.Z,{template:"jest-react",params:{tests:"open"}}),"\n",(0,r.jsx)(t.h2,{id:"tests-panel",children:"Tests Panel"}),"\n",(0,r.jsxs)(t.p,{children:['The "Tests" panel is located in the "',(0,r.jsx)(t.a,{href:"/docs/features/tools-pane",children:"Tools pane"}),'" below the result page.']}),"\n",(0,r.jsx)(t.p,{children:"In the tests panel, you can find:"}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsx)(t.li,{children:'"Run" button: To run tests (keyboard shortcut: Ctrl/Cmd + Alt + t).'}),"\n",(0,r.jsx)(t.li,{children:'"Watch" button toggle: To watch the project and re-run tests automatically when code changes.'}),"\n",(0,r.jsx)(t.li,{children:'"Reset" button: Resets test results.'}),"\n",(0,r.jsx)(t.li,{children:'"Edit" button: Opens a code editor to edit tests (not in embeds).'}),"\n",(0,r.jsx)(t.li,{children:"Test results."}),"\n"]}),"\n",(0,r.jsxs)(t.admonition,{title:"Note",type:"info",children:[(0,r.jsxs)(t.p,{children:["Please note that the tests panel are hidden by default in ",(0,r.jsx)(t.a,{href:"/docs/features/embeds",children:"embedded playgrounds"})," unless the ",(0,r.jsx)(t.a,{href:"/docs/configuration/configuration-object#tests",children:"project has tests"}),". In such case, the panel is added to the ",(0,r.jsx)(t.a,{href:"/docs/features/tools-pane",children:"tools pane"}),". However, the test editor is not shown."]}),(0,r.jsxs)(t.p,{children:["The ",(0,r.jsx)(t.a,{href:"/docs/sdk/",children:"SDK"})," can control the visibility of the different tools in the tools pane (see ",(0,r.jsx)(t.a,{href:"/docs/configuration/configuration-object#tools",children:(0,r.jsx)(t.code,{children:"tools"})})," property of the ",(0,r.jsx)(t.a,{href:"/docs/configuration/configuration-object",children:"configuration object"}),")."]}),(0,r.jsxs)(t.p,{children:["The tests panel and the test editor are always shown in the ",(0,r.jsx)(t.a,{href:"/docs/getting-started#standalone-app",children:"full standalone app"}),"."]})]}),"\n",(0,r.jsx)(t.h2,{id:"supported-languages",children:"Supported Languages"}),"\n",(0,r.jsx)(t.p,{children:"The testing code can be written using JavaScript, TypeScript, JSX or TSX.\nHowever, since the tests run against the result web page, they can test projects that use any language/framework."}),"\n",(0,r.jsxs)(t.p,{children:["This is ",(0,r.jsx)(t.a,{href:"https://livecodes.io/?x=id/xyi6usem2sf&tests",children:"a demo"})," for running tests against a Ruby project."]}),"\n",(0,r.jsx)(o.Z,{import:"id/xyi6usem2sf",params:{tests:"open"},height:"80vh"}),"\n",(0,r.jsxs)(t.p,{children:["Languages may have test modules. This is ",(0,r.jsx)(t.a,{href:"https://livecodes.io/?x=id/665ar3bpqka&console=full",children:"an example"})," of running ",(0,r.jsx)(t.a,{href:"https://docs.python.org/3/library/doctest.html",children:"Python doctest"})," tests:"]}),"\n",(0,r.jsx)(o.Z,{import:"id/665ar3bpqka",params:{console:"full"},height:"80vh"}),"\n",(0,r.jsx)(t.h2,{id:"importing-code",children:"Importing Code"}),"\n",(0,r.jsxs)(t.p,{children:["Functions, objects or values can be exported from the ",(0,r.jsx)(t.code,{children:"script"})," code like a regular ES module.\nThese can then be imported in the test code for usage. This is only available for code in the ",(0,r.jsx)(t.code,{children:"script"})," editor. The testing code also have access to global objects like ",(0,r.jsx)(t.code,{children:"window"}),"."]}),"\n",(0,r.jsx)(t.p,{children:"Example:"}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-js",children:"// in the script editor\nexport default function greet() {\n return 'Hello, World!';\n}\n\nexport const add = (x, y) => x + y;\n\nwindow.multiply = (x, y) => x * y;\n"})}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-js",children:"// in the test editor\nimport greet, { add } from './script'; // relative import without extension\n\ndescribe('test imported', () => {\n test('greet', () => {\n expect(greet()).toBe('Hello, World!');\n });\n\n test('add', () => {\n expect(add(1, 2)).toBe(3);\n });\n});\n\ndescribe('test global', () => {\n test('multiply', () => {\n expect(window.multiply(2, 3)).toBe(6);\n });\n});\n"})}),"\n",(0,r.jsx)(t.h2,{id:"supported-jest-features",children:"Supported Jest features"}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.a,{href:"https://jestjs.io/docs/api",children:"Jest globals"}),": ",(0,r.jsx)(t.code,{children:"expect"}),", ",(0,r.jsx)(t.code,{children:"test"}),", ",(0,r.jsx)(t.code,{children:"xtest"}),", ",(0,r.jsx)(t.code,{children:"it"}),", ",(0,r.jsx)(t.code,{children:"fit"}),", ",(0,r.jsx)(t.code,{children:"xit"}),", ",(0,r.jsx)(t.code,{children:"describe"}),", ",(0,r.jsx)(t.code,{children:"fdescribe"}),", ",(0,r.jsx)(t.code,{children:"xdescribe"}),", ",(0,r.jsx)(t.code,{children:"beforeAll"}),", ",(0,r.jsx)(t.code,{children:"afterAll"}),", ",(0,r.jsx)(t.code,{children:"beforeEach"}),", ",(0,r.jsx)(t.code,{children:"afterEach"})]}),"\n",(0,r.jsxs)(t.li,{children:["Jest function mocks: ",(0,r.jsx)(t.code,{children:"jest.fn"}),", ",(0,r.jsx)(t.code,{children:"jest.mocked"}),", ",(0,r.jsx)(t.code,{children:"jest.replaceProperty"}),", ",(0,r.jsx)(t.code,{children:"jest.spyOn"})]}),"\n"]}),"\n",(0,r.jsx)(t.p,{children:"These can be directly used in the test editor, without the need for any imports.\nAutocomplete is available in Monaco editor for Jest API."}),"\n",(0,r.jsx)(t.h2,{id:"supported-testing-libraries",children:"Supported testing libraries"}),"\n",(0,r.jsx)(t.p,{children:"In addition to Jest, you may wish to use other supported testing libraries. These have to be explicitly imported to the testing code."}),"\n",(0,r.jsx)(t.h3,{id:"testing-library",children:"Testing library"}),"\n",(0,r.jsx)(t.p,{children:"Simple and complete testing utilities that encourage good testing practices."}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsxs)(t.li,{children:["\n",(0,r.jsx)("a",{href:"https://testing-library.com/docs/dom-testing-library/intro",target:"_blank",children:"DOM Testing Library"}),"\n"]}),"\n"]}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-js",children:"import {\n getByLabelText,\n getByText,\n getByTestId,\n queryByTestId,\n waitFor,\n} from '@testing-library/dom';\n"})}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsxs)(t.li,{children:["\n",(0,r.jsx)("a",{href:"https://testing-library.com/docs/react-testing-library/intro",target:"_blank",children:"React Testing Library"}),"\n"]}),"\n"]}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-js",children:"import { render, fireEvent, waitFor, screen } from '@testing-library/react';\n"})}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsxs)(t.li,{children:["\n",(0,r.jsx)("a",{href:"https://testing-library.com/docs/ecosystem-jest-dom",target:"_blank",children:"jest-dom"}),"\n"]}),"\n"]}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-js",children:"import '@testing-library/jest-dom';\n"})}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsxs)(t.li,{children:["\n",(0,r.jsx)("a",{href:"https://testing-library.com/docs/user-event/intro",target:"_blank",children:"user-event"}),"\n"]}),"\n"]}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-js",children:"import userEvent from '@testing-library/user-event';\n"})}),"\n",(0,r.jsx)(t.h3,{id:"chai",children:"Chai"}),"\n",(0,r.jsx)(t.p,{children:"Jest assertions can be used in the tests. However, if you prefer Chai, it can be easily used.\nAutocomplete is also available in Monaco editor for Chai API."}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-js",children:"import { assert } from 'chai';\n"})}),"\n",(0,r.jsx)(t.h2,{id:"examples",children:"Examples"}),"\n",(0,r.jsxs)(t.p,{children:["Usage examples are provided in the starter templates (",(0,r.jsx)("a",{href:"pathname:///../?template=jest",target:"_blank",children:"Jest Starter"})," and ",(0,r.jsx)("a",{href:"pathname:///../?template=jest-react",target:"_blank",children:"Jest/React Starter"}),")."]}),"\n",(0,r.jsx)(t.admonition,{type:"caution",children:(0,r.jsx)(t.p,{children:"The test code is added to the result page and runs in its context. Please note that script errors (e.g. import or syntax errors) may prevent the tests from loading."})}),"\n",(0,r.jsx)(t.h2,{id:"sdk",children:"SDK"}),"\n",(0,r.jsxs)(t.p,{children:["The ",(0,r.jsx)(t.a,{href:"/docs/sdk/",children:"SDK"})," allows ",(0,r.jsx)(t.a,{href:"/docs/sdk/js-ts#runtests",children:"running tests"})," and collecting results."]})]})}function p(e={}){let{wrapper:t}={...(0,i.a)(),...e.components};return t?(0,r.jsx)(t,{...e,children:(0,r.jsx)(h,{...e})}):h(e)}},2580:function(e,t,s){s.d(t,{Z:function(){return n}});let n=s.p+"assets/images/test-editor-0186c1c97faf3bf597fea218a63fdb0e.jpg"},9493:function(e,t,s){s.d(t,{Z:function(){return n}});let n=s.p+"assets/images/tests-99a062bb017d23a722610e968fbfca2a.jpg"},3365:function(e,t,s){s.d(t,{Z:()=>f});var n=s("5893"),r=s("4200"),i=s("7294"),o=s("8294");function a(e){let t=(0,i.useRef)(null),[s,r]=(0,i.useState)(e.className||""),[a,l]=(0,i.useState)(e.style||{}),[d,c]=(0,i.useState)(e.height),[h,p]=(0,i.useState)(),[u,m]=(0,i.useState)(JSON.stringify(e.config||"")),[g,f]=(0,i.useState)("");return(0,i.useEffect)(()=>{if(!t.current)return;let{className:s,style:n,height:i,sdkReady:a,config:d,...j}=e;if(r(s||""),l(n||{}),c(i),h&&g===JSON.stringify(j)){if(u===JSON.stringify(d))return;m(JSON.stringify(d)),"string"==typeof d?fetch(d).then(e=>e.json()).then(e=>{h?.setConfig(e)}):d&&h.setConfig(d)}else f(JSON.stringify(j)),h?.destroy(),(0,o.T)(t.current,{config:d,...j}).then(e=>{p(e),"function"==typeof a&&a(e)})},[e]),(0,i.useEffect)(()=>()=>{h?.destroy()},[]),(0,n.jsx)("div",{ref:t,className:s,style:a,"data-height":d})}var l=s("1858"),d=s("3262"),c=s("1705"),h=s("7645"),p=s("8168"),u=s("8228"),m=s("5050");function g(e){let[t,s]=(0,i.useState)(e.js),[r,o]=(0,i.useState)(e.ts),[a,l]=(0,i.useState)(e.react),[g,f]=(0,i.useState)(e.vue),[j,x]=(0,i.useState)(e.svelte),y="3.7rem",[v,b]=(0,i.useState)(!0),[w,S]=(0,i.useState)(y),T=(0,i.useRef)(null),C=()=>{setTimeout(()=>{S(`calc(${T.current.offsetHeight}px + ${y})`)},5),setTimeout(()=>{S(`calc(${T.current.offsetHeight}px + ${y})`)},255)};return(0,i.useEffect)(()=>{if(d.Z.canUseDOM){let e=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"js";try{return window.prettier?.format(e,{parser:"html"===t?"html":"babel",plugins:window.prettierPlugins})}catch{return e}};s(e(t,"js")),o(e(r,"ts")),l(e(a,"jsx")),f(e(g,"html")),x(e(j,"html"))}},[]),(0,n.jsxs)("details",{className:`alert alert--info ${m.Z.details} ${u.Z.details}`,"data-collapsed":v,style:{height:v?y:w,overflow:"hidden",willChange:"height",transition:`height ${v?"250ms":"265ms"} ease-in-out 0s`,margin:"1em 0"},children:[(0,n.jsx)("summary",{onClick:()=>{b(!v),C()},children:"show code"}),(0,n.jsx)("div",{ref:T,style:{display:"block",overflow:"hidden"},children:(0,n.jsx)("div",{className:m.Z.collapsibleContent,children:(0,n.jsxs)(p.Z,{groupId:"sdk-code",children:[(0,n.jsx)(h.Z,{value:"js",label:"JS",attributes:{onMouseDown:C},children:(0,n.jsx)(c.Z,{language:"js",children:t})}),(0,n.jsx)(h.Z,{value:"ts",label:"TS",attributes:{onMouseDown:C},children:(0,n.jsx)(c.Z,{language:"ts",children:r})}),(0,n.jsx)(h.Z,{value:"react",label:"React",attributes:{onMouseDown:C},children:(0,n.jsx)(c.Z,{language:"jsx",children:a})}),(0,n.jsx)(h.Z,{value:"vue",label:"Vue",attributes:{onMouseDown:C},children:(0,n.jsx)(c.Z,{language:"html",children:g})}),(0,n.jsx)(h.Z,{value:"svelte",label:"Svelte",attributes:{onMouseDown:C},children:(0,n.jsx)(c.Z,{language:"html",children:j})})]})})})]})}function f(e){let{className:t,style:s,showCode:i,height:o,...d}=e,{colorMode:c}=(0,r.I)(),h=e=>JSON.stringify(e,null,2),p=`
|
|
import { createPlayground } from 'livecodes';
|
|
|
|
const options = ${h(d)};
|
|
createPlayground('#container', options);
|
|
|
|
`.trimStart(),u=`
|
|
import { createPlayground, type EmbedOptions } from 'livecodes';
|
|
|
|
const options: EmbedOptions = ${h(d)};
|
|
createPlayground('#container', options);
|
|
|
|
`.trimStart(),m=`
|
|
import LiveCodes from 'livecodes/react';
|
|
|
|
export default function App() {
|
|
const options = ${h(d)};
|
|
return (<LiveCodes {...options}></LiveCodes>);
|
|
}
|
|
|
|
`.trimStart(),f=`
|
|
<script setup>
|
|
import LiveCodes from "livecodes/vue";
|
|
|
|
const options = ${h(d)};
|
|
</script>
|
|
<template>
|
|
<LiveCodes v-bind="options" />
|
|
</template>
|
|
|
|
`,j=`
|
|
<script>
|
|
import { onMount } from 'svelte';
|
|
import { createPlayground } from 'livecodes';
|
|
|
|
let options = $state(${h(d)});
|
|
let container = $state(null);
|
|
onMount(() => {
|
|
createPlayground(container, options);
|
|
});
|
|
</script>
|
|
|
|
<div bind:this="{container}"></div>
|
|
|
|
`.trimStart();return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(a,{className:`container_Egsj ${e.className}`,style:{height:o||"50vh",...e.style},appUrl:l.G,...e,config:{theme:c,themeColor:"hsl(215, 8%, 60%)",..."object"==typeof e.config?e.config:{}}}),!1!==e.showCode&&(0,n.jsx)(g,{js:p,ts:u,react:m,vue:f,svelte:j})]})}},8294:function(e,t,s){s.d(t,{T:function(){return r},r:function(){return i}});var n=s(7728);async function r(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"object"!=typeof e||e instanceof HTMLElement||!e.headless&&"headless"!==e.view||(t=e,e=null);let{config:s={},headless:n,loading:r="lazy",view:o}=t,a=n||"headless"===o,l=null,d=null;if("string"==typeof e)l=document.querySelector(e);else if(e instanceof HTMLElement)l=e;else if(!(a&&"object"==typeof e))throw Error("A valid container element is required.");if(!l){if(a)T(l=document.createElement("div")),document.body.appendChild(l);else throw Error(`Cannot find element: "${e}"`)}let c=new URL(i(t)),h=c.origin;c.searchParams.set("embed","true"),c.searchParams.set("loading",a?"eager":r),c.searchParams.set("sdkVersion",process.env.SDK_VERSION||"latest"),"object"==typeof s&&Object.keys(s).length>0&&c.searchParams.set("config","sdk");let p=t.params;"object"==typeof p&&Object.keys(p).length>0&&JSON.stringify(p).length<1800&&Object.keys(p).forEach(e=>{c.searchParams.set(e,encodeURIComponent(String(p[e])))});let u=!1,m="Cannot call API methods after calling `destroy()`.",g=await new Promise(e=>{if(!l)return;let t=l.dataset.height||l.style.height;if(t&&!a){let e=isNaN(Number(t))?t:t+"px";l.style.height=e}"false"===l.dataset.defaultStyles||a||(l.style.backgroundColor||="#fff",l.style.border||="1px solid black",l.style.borderRadius||="8px",l.style.boxSizing||="border-box",l.style.padding||="0",l.style.width||="100%",l.style.height||=l.style.height||"300px",l.style.minHeight="200px",l.style.flexGrow="1",l.style.overflow||="hidden",l.style.resize||="vertical");let n="livecodes",i=l.querySelector(`iframe.${n}`),o=i||document.createElement("iframe");o.classList.add(n),o.setAttribute("allow","accelerometer; camera; encrypted-media; display-capture; geolocation; gyroscope; microphone; midi; clipboard-read; clipboard-write; web-share"),o.setAttribute("allowtransparency","true"),o.setAttribute("allowpaymentrequest","true"),o.setAttribute("allowfullscreen","true"),o.setAttribute("sandbox","allow-same-origin allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts"),o.setAttribute("loading","eager"===r?"eager":"lazy"),a?T(o):(o.style.height="100%",o.style.minHeight="200px",o.style.width="100%",o.style.margin="0",o.style.border="0",o.style.borderRadius=l.style.borderRadius),addEventListener("message",function e(t){t.source===o.contentWindow&&t.origin===h&&t.data?.type==="livecodes-init"&&(removeEventListener("message",e),d=Number(t.data.payload.appVersion.replace(/^v/,"")))}),(!d||d<46)&&addEventListener("message",function e(t){t.source===o.contentWindow&&t.origin===h&&t.data?.type==="livecodes-get-config"&&(removeEventListener("message",e),o.contentWindow?.postMessage({type:"livecodes-config",payload:s},h))}),o.onload=()=>{e(o)},o.src=c.href,i||l.appendChild(o)}),f=new Promise(e=>{addEventListener("message",function t(s){s.source===g.contentWindow&&s.origin===h&&s.data?.type==="livecodes-ready"&&(removeEventListener("message",t),e(),f.settled=!0)})}),j=()=>u?Promise.reject(m):new Promise(async e=>{f.settled&&e(),g.contentWindow?.postMessage({type:"livecodes-load"},h),await f,e()}),x=(e,t)=>new Promise(async(s,n)=>{if(u)return n(m);await j();let r=C();addEventListener("message",function t(i){if(i.source===g.contentWindow&&i.origin===h&&i.data?.type==="livecodes-api-response"&&i.data?.id===r&&i.data.method===e){removeEventListener("message",t);let e=i.data.payload;e?.error?n(e.error):s(e)}}),g.contentWindow?.postMessage({method:e,id:r,args:t},h)}),y={},v=["load","ready","code","console","tests","destroy"],b=(e,t)=>{if(u)throw Error(m);return v.includes(e)?(x("watch",[e]),y[e]||(y[e]=[]),y[e]?.push(t),{remove:()=>{y[e]=y[e]?.filter(e=>e!==t),y[e]?.length===0&&x("watch",[e,"unsubscribe"])}}):{remove:()=>void 0}},w=e=>({"livecodes-app-loaded":"load","livecodes-ready":"ready","livecodes-change":"code","livecodes-console":"console","livecodes-test-results":"tests","livecodes-destroy":"destroy"})[e];addEventListener("message",async e=>{let t=w(e.data?.type??"");if(e.source!==g.contentWindow||e.origin!==h||!t||!y[t])return;let s=e.data?.payload;y[t]?.forEach(e=>{e(s)})});let S=()=>{Object.values(y).forEach(e=>{e.length=0}),g?.remove?.(),u=!0};function T(e){e.style.position="absolute",e.style.top="0",e.style.visibility="hidden",e.style.opacity="0"}"lazy"===r&&"IntersectionObserver"in window&&new IntersectionObserver((e,t)=>{e.forEach(async e=>{e.isIntersecting&&(await j(),t.unobserve(l))})},{rootMargin:"150px"}).observe(l);let C=()=>(String(Math.random())+Date.now().toFixed()).replace("0.","");return{load:()=>j(),run:()=>x("run"),format:e=>x("format",[e]),getShareUrl:e=>x("getShareUrl",[e]),getConfig:e=>x("getConfig",[e]),setConfig:e=>x("setConfig",[e]),getCode:()=>x("getCode"),show:(e,t)=>x("show",[e,t]),runTests:()=>x("runTests"),onChange:e=>b("code",e),watch:b,exec:function(e){for(var t=arguments.length,s=Array(t>1?t-1:0),n=1;n<t;n++)s[n-1]=arguments[n];return x("exec",[e,...s])},destroy:()=>f.settled?x("destroy").then(S):u?Promise.reject(m):(S(),Promise.resolve())}}function i(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{appUrl:s="https://livecodes.io",params:r={},config:i={},headless:o,import:a,lite:l,view:d,...c}=t;try{e=new URL(s)}catch{throw Error(`${s} is not a valid URL.`)}let h=new URLSearchParams;Object.entries(c).forEach(t=>{let[s,n]=t;void 0!==n&&e.searchParams.set(s,String(n))});let p="headless"===t.view||o;if(l&&(console.warn('Deprecation notice: "lite" option is deprecated. Use "config: { mode: \'lite\' }" instead.'),"object"==typeof i&&null==i.mode?i.mode="lite":e.searchParams.set("lite","true")),d&&(console.warn('Deprecation notice: The "view" option has been moved to "config.view". For headless mode use "headless: true".'),"object"==typeof i&&null==i.view&&"headless"!==d?i.view=d:e.searchParams.set("view",d)),"string"==typeof i)try{new URL(i),e.searchParams.set("config",encodeURIComponent(i))}catch{throw Error('"config" is not a valid URL or configuration object.')}else i&&"object"==typeof i&&Object.keys(i).length>0&&(i.title&&"Untitled Project"!==i.title&&e.searchParams.set("title",i.title),i.description&&i.description.length>0&&e.searchParams.set("description",i.description),h.set("config","code/"+(0,n.compressToEncodedURIComponent)(JSON.stringify(i))));if(r&&"object"==typeof r&&Object.keys(r).length>0)try{h.set("params",(0,n.compressToEncodedURIComponent)(JSON.stringify(r)))}catch{Object.keys(r).forEach(t=>{e.searchParams.set(t,encodeURIComponent(String(r[t])))})}return a&&e.searchParams.set("x",encodeURIComponent(a)),p&&e.searchParams.set("headless","true"),e.hash=h.toString(),e.href}},65:function(e,t,s){s.d(t,{Z:function(){return a},a:function(){return o}});var n=s(7294);let r={},i=n.createContext(r);function o(e){let t=n.useContext(i);return n.useMemo(function(){return"function"==typeof e?e(t):{...t,...e}},[t,e])}function a(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(r):e.components||r:o(e.components),n.createElement(i.Provider,{value:t},e.children)}}}]); |