"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["823"],{4944:function(e,t,s){s.r(t),s.d(t,{UMDCode:()=>g,default:()=>y,frontMatter:()=>h,metadata:()=>n,assets:()=>u,ESMCode:()=>m,toc:()=>f,contentTitle:()=>p});var n=JSON.parse('{"id":"sdk/index","title":"LiveCodes SDK","description":"The Software Development Kit (SDK) provides an easy, yet powerful, interface to embed and communicate with LiveCodes playgrounds.","source":"@site/docs/sdk/index.mdx","sourceDirName":"sdk","slug":"/sdk/","permalink":"/docs/sdk/","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/sdk/index.mdx","tags":[],"version":"current","frontMatter":{"sidebar_class_name":"exclude_from_sidebar"},"sidebar":"docsSidebar","previous":{"title":"Query Parameters","permalink":"/docs/configuration/query-params"},"next":{"title":"JS/TS SDK","permalink":"/docs/sdk/js-ts"}}'),o=s("5893"),r=s("65"),i=s("8168"),a=s("7645"),l=s("3365"),d=s("7262"),c=s("1705");let h={sidebar_class_name:"exclude_from_sidebar"},p="LiveCodes SDK",u={},m=()=>{let{siteConfig:e}=(0,d.Z)();return(0,o.jsx)(c.Z,{title:"index.html",language:"html",children:`
`})},g=()=>{let{siteConfig:e}=(0,d.Z)();return(0,o.jsx)(c.Z,{title:"index.html",language:"html",children:`
`})},f=[{value:"SDK Demo",id:"sdk-demo",level:2},{value:"Installation",id:"installation",level:2},{value:"NPM Package",id:"npm-package",level:3},{value:"CDN",id:"cdn",level:3},{value:"Usage",id:"usage",level:2},{value:"Headless Mode",id:"headless-mode",level:2},{value:"SDK Playground!",id:"sdk-playground",level:2}];function v(e){let t={a:"a",admonition:"admonition",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",li:"li",p:"p",pre:"pre",ul:"ul",...(0,r.a)(),...e.components};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(t.header,{children:(0,o.jsx)(t.h1,{id:"livecodes-sdk",children:"LiveCodes SDK"})}),"\n","\n",(0,o.jsx)(t.p,{children:"The Software Development Kit (SDK) provides an easy, yet powerful, interface to embed and communicate with LiveCodes playgrounds."}),"\n",(0,o.jsxs)(t.p,{children:["The SDK is provided as a light-weight (",(0,o.jsx)(t.a,{href:"https://bundlephobia.com/package/livecodes",children:"less than 5kb gzipped"}),"), zero-dependencies ",(0,o.jsx)(t.a,{href:"#npm-package",children:"npm package"}),", that is also available from ",(0,o.jsx)(t.a,{href:"#cdn",children:"CDNs"}),". It can be used to create playgrounds with a wide variety of ",(0,o.jsx)(t.a,{href:"/docs/configuration/configuration-object",children:"configurations"})," and ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#embed-options",children:"embed options"}),". In addition, ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#sdk-methods",children:"SDK methods"})," allow programmatic communication and control of the playgrounds during runtime."]}),"\n",(0,o.jsxs)(t.p,{children:["The ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts",children:"JavaScript SDK"})," is framework/library agnostic. However, wrapper components are also provided for popular libraries (currently ",(0,o.jsx)(t.a,{href:"/docs/sdk/react",children:"React"})," and ",(0,o.jsx)(t.a,{href:"/docs/sdk/vue",children:"Vue"}),"). The SDK can be used in ",(0,o.jsx)(t.a,{href:"/docs/sdk/svelte",children:"Svelte"})," directly without wrappers. ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#typescript-types",children:"TypeScript support"})," provides type-safety and a great developer experience."]}),"\n",(0,o.jsx)(t.h2,{id:"sdk-demo",children:"SDK Demo"}),"\n",(0,o.jsx)(t.p,{children:"This is an example of an editable embedded playground using the SDK."}),"\n",(0,o.jsx)(l.Z,{config:{markup:{language:"markdown",content:"# Hello World!"},script:{language:"javascript",content:'console.log("Hello, from JS!");'},tools:{active:"console",status:"open"}}}),"\n",(0,o.jsx)(t.h2,{id:"installation",children:"Installation"}),"\n",(0,o.jsx)(t.h3,{id:"npm-package",children:"NPM Package"}),"\n",(0,o.jsx)(t.p,{children:"This is a single npm package for the SDK which supports JavaScript/TypeScript, React, Vue and Svelte.\nInstall the library from npm:"}),"\n",(0,o.jsxs)(i.Z,{groupId:"npm2yarn",children:[(0,o.jsx)(a.Z,{value:"npm",children:(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-bash",children:"npm install livecodes\n"})})}),(0,o.jsx)(a.Z,{value:"yarn",label:"Yarn",children:(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-bash",children:"yarn add livecodes\n"})})}),(0,o.jsx)(a.Z,{value:"pnpm",label:"pnpm",children:(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-bash",children:"pnpm add livecodes\n"})})}),(0,o.jsx)(a.Z,{value:"bun",label:"Bun",children:(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-bash",children:"bun add livecodes\n"})})})]}),"\n",(0,o.jsx)(t.p,{children:"then it can be used like that:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-js",metastring:'title="index.js"',children:"import { createPlayground } from 'livecodes';\n\ncreatePlayground('#container', {\n // embed options\n});\n"})}),"\n",(0,o.jsx)(t.h3,{id:"cdn",children:"CDN"}),"\n",(0,o.jsx)(t.p,{children:"Alternatively, it can just be loaded from a CDN."}),"\n",(0,o.jsx)(t.p,{children:"ESM:"}),"\n","\n","\n",(0,o.jsx)(m,{}),"\n",(0,o.jsx)(t.p,{children:"UMD:"}),"\n","\n",(0,o.jsx)(g,{}),"\n",(0,o.jsx)(t.admonition,{type:"info",children:(0,o.jsxs)(t.p,{children:["In the full ",(0,o.jsx)(t.a,{href:"/docs/getting-started#standalone-app",children:"standalone app"}),", the JavaScript SDK is accessible via the global variable ",(0,o.jsx)(t.code,{children:"livecodes"}),", which can be interacted with in the browser console."]})}),"\n",(0,o.jsx)(t.h2,{id:"usage",children:"Usage"}),"\n",(0,o.jsx)(t.p,{children:"The SDK is currently provided in the following variations:"}),"\n",(0,o.jsxs)(t.ul,{children:["\n",(0,o.jsxs)(t.li,{children:["\n",(0,o.jsx)(t.p,{children:(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts",children:"JavaScript/TypeScript"})}),"\n"]}),"\n",(0,o.jsxs)(t.li,{children:["\n",(0,o.jsx)(t.p,{children:(0,o.jsx)(t.a,{href:"/docs/sdk/react",children:"React"})}),"\n"]}),"\n",(0,o.jsxs)(t.li,{children:["\n",(0,o.jsx)(t.p,{children:(0,o.jsx)(t.a,{href:"/docs/sdk/vue",children:"Vue"})}),"\n"]}),"\n",(0,o.jsxs)(t.li,{children:["\n",(0,o.jsx)(t.p,{children:(0,o.jsx)(t.a,{href:"/docs/sdk/svelte",children:"Svelte"})}),"\n"]}),"\n"]}),"\n",(0,o.jsx)(t.h2,{id:"headless-mode",children:"Headless Mode"}),"\n",(0,o.jsxs)(t.p,{children:["The SDK also has a ",(0,o.jsx)(t.a,{href:"/docs/sdk/headless",children:"headless mode"}),". In this mode, no visible output is displayed in the embedding web page. However, all ",(0,o.jsx)(t.a,{href:"/docs/sdk/js-ts#sdk-methods",children:"SDK methods"})," are accessible. This provides the power of leveraging the wide range of features and language support offered by LiveCodes, while retaining full control over the UI."]}),"\n",(0,o.jsx)(t.h2,{id:"sdk-playground",children:"SDK Playground!"}),"\n",(0,o.jsxs)(t.p,{children:["A demo page that shows the usage of the SDK can be ",(0,o.jsx)(t.a,{href:"https://live-codes.github.io/livecodes-examples/sdk-demo.html",children:"found here"})," (",(0,o.jsx)(t.a,{href:"https://github.com/live-codes/livecodes-examples/blob/gh-pages/sdk-demo.html",children:"source"}),")."]}),"\n",(0,o.jsx)(t.p,{children:"Or edit the SDK playground in LiveCodes. How meta! :)"}),"\n",(0,o.jsx)(l.Z,{import:"id/8k6vbxitvb9",config:{view:"result"},height:"80vh",showCode:!1}),"\n",(0,o.jsx)(t.p,{children:'P.S. You may want to use the "Full Screen" button!'})]})}function y(e={}){let{wrapper:t}={...(0,r.a)(),...e.components};return t?(0,o.jsx)(t,{...e,children:(0,o.jsx)(v,{...e})}):v(e)}},3365:function(e,t,s){s.d(t,{Z:()=>f});var n=s("5893"),o=s("4200"),r=s("7294"),i=s("8294");function a(e){let t=(0,r.useRef)(null),[s,o]=(0,r.useState)(e.className||""),[a,l]=(0,r.useState)(e.style||{}),[d,c]=(0,r.useState)(e.height),[h,p]=(0,r.useState)(),[u,m]=(0,r.useState)(JSON.stringify(e.config||"")),[g,f]=(0,r.useState)("");return(0,r.useEffect)(()=>{if(!t.current)return;let{className:s,style:n,height:r,sdkReady:a,config:d,...v}=e;if(o(s||""),l(n||{}),c(r),h&&g===JSON.stringify(v)){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(v)),h?.destroy(),(0,i.T)(t.current,{config:d,...v}).then(e=>{p(e),"function"==typeof a&&a(e)})},[e]),(0,r.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,r.useState)(e.js),[o,i]=(0,r.useState)(e.ts),[a,l]=(0,r.useState)(e.react),[g,f]=(0,r.useState)(e.vue),[v,y]=(0,r.useState)(e.svelte),j="3.7rem",[x,b]=(0,r.useState)(!0),[w,S]=(0,r.useState)(j),k=(0,r.useRef)(null),C=()=>{setTimeout(()=>{S(`calc(${k.current.offsetHeight}px + ${j})`)},5),setTimeout(()=>{S(`calc(${k.current.offsetHeight}px + ${j})`)},255)};return(0,r.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")),i(e(o,"ts")),l(e(a,"jsx")),f(e(g,"html")),y(e(v,"html"))}},[]),(0,n.jsxs)("details",{className:`alert alert--info ${m.Z.details} ${u.Z.details}`,"data-collapsed":x,style:{height:x?j:w,overflow:"hidden",willChange:"height",transition:`height ${x?"250ms":"265ms"} ease-in-out 0s`,margin:"1em 0"},children:[(0,n.jsx)("summary",{onClick:()=>{b(!x),C()},children:"show code"}),(0,n.jsx)("div",{ref:k,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:o})}),(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:v})})]})})})]})}function f(e){let{className:t,style:s,showCode:r,height:i,...d}=e,{colorMode:c}=(0,o.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 (); } `.trimStart(),f=` `,v=`
`.trimStart();return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(a,{className:`container_Egsj ${e.className}`,style:{height:i||"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:v})]})}},8294:function(e,t,s){s.d(t,{T:function(){return o},r:function(){return r}});var n=s(7728);async function o(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:o="lazy",view:i}=t,a=n||"headless"===i,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)C(l=document.createElement("div")),document.body.appendChild(l);else throw Error(`Cannot find element: "${e}"`)}let c=new URL(r(t)),h=c.origin;c.searchParams.set("embed","true"),c.searchParams.set("loading",a?"eager":o);let p=globalThis.process;c.searchParams.set("sdkVersion",p?.env?.SDK_VERSION||"latest"),"object"==typeof s&&Object.keys(s).length>0&&c.searchParams.set("config","sdk");let u=t.params;"object"==typeof u&&Object.keys(u).length>0&&JSON.stringify(u).length<1800&&Object.keys(u).forEach(e=>{c.searchParams.set(e,encodeURIComponent(String(u[e])))});let m=!1,g="Cannot call API methods after calling `destroy()`.",f=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",r=l.querySelector(`iframe.${n}`),i=r||document.createElement("iframe");i.classList.add(n),i.setAttribute("allow","accelerometer; camera; encrypted-media; display-capture; geolocation; gyroscope; microphone; midi; clipboard-read; clipboard-write; web-share"),i.setAttribute("allowtransparency","true"),i.setAttribute("allowpaymentrequest","true"),i.setAttribute("allowfullscreen","true"),i.setAttribute("sandbox","allow-same-origin allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts"),i.setAttribute("loading","eager"===o?"eager":"lazy"),a?C(i):(i.style.height="100%",i.style.minHeight="200px",i.style.width="100%",i.style.margin="0",i.style.border="0",i.style.borderRadius=l.style.borderRadius),addEventListener("message",function e(t){t.source===i.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===i.contentWindow&&t.origin===h&&t.data?.type==="livecodes-get-config"&&(removeEventListener("message",e),i.contentWindow?.postMessage({type:"livecodes-config",payload:s},h))}),i.onload=()=>{e(i)},i.src=c.href,r||l.appendChild(i)}),v=new Promise(e=>{addEventListener("message",function t(s){s.source===f.contentWindow&&s.origin===h&&s.data?.type==="livecodes-ready"&&(removeEventListener("message",t),e(),v.settled=!0)})}),y=()=>m?Promise.reject(g):new Promise(async e=>{v.settled&&e(),f.contentWindow?.postMessage({type:"livecodes-load"},h),await v,e()}),j=(e,t)=>new Promise(async(s,n)=>{if(m)return n(g);await y();let o=P();addEventListener("message",function t(r){if(r.source===f.contentWindow&&r.origin===h&&r.data?.type==="livecodes-api-response"&&r.data?.id===o&&r.data.method===e){removeEventListener("message",t);let e=r.data.payload;e?.error?n(e.error):s(e)}}),f.contentWindow?.postMessage({method:e,id:o,args:t},h)}),x={},b=["load","ready","code","console","tests","destroy"],w=(e,t)=>{if(m)throw Error(g);return b.includes(e)?(j("watch",[e]),x[e]||(x[e]=[]),x[e]?.push(t),{remove:()=>{x[e]=x[e]?.filter(e=>e!==t),x[e]?.length===0&&j("watch",[e,"unsubscribe"])}}):{remove:()=>void 0}},S=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=S(e.data?.type??"");if(e.source!==f.contentWindow||e.origin!==h||!t||!x[t])return;let s=e.data?.payload;x[t]?.forEach(e=>{e(s)})});let k=()=>{Object.values(x).forEach(e=>{e.length=0}),f?.remove?.(),m=!0};function C(e){e.style.position="absolute",e.style.top="0",e.style.visibility="hidden",e.style.opacity="0"}"lazy"===o&&"IntersectionObserver"in window&&new IntersectionObserver((e,t)=>{e.forEach(async e=>{e.isIntersecting&&(await y(),t.unobserve(l))})},{rootMargin:"150px"}).observe(l);let P=()=>(String(Math.random())+Date.now().toFixed()).replace("0.","");return{load:()=>y(),run:()=>j("run"),format:e=>j("format",[e]),getShareUrl:e=>j("getShareUrl",[e]),getConfig:e=>j("getConfig",[e]),setConfig:e=>j("setConfig",[e]),getCode:()=>j("getCode"),show:(e,t)=>j("show",[e,t]),runTests:()=>j("runTests"),onChange:e=>w("code",e),watch:w,exec:function(e){for(var t=arguments.length,s=Array(t>1?t-1:0),n=1;nv.settled?j("destroy").then(k):m?Promise.reject(g):(k(),Promise.resolve())}}function r(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{appUrl:s="https://livecodes.io",params:o={},config:r={},headless:i,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||i;if(l&&(console.warn('Deprecation notice: "lite" option is deprecated. Use "config: { mode: \'lite\' }" instead.'),"object"==typeof r&&null==r.mode?r.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 r&&null==r.view&&"headless"!==d?r.view=d:e.searchParams.set("view",d)),"string"==typeof r)try{new URL(r),e.searchParams.set("config",encodeURIComponent(r))}catch{throw Error('"config" is not a valid URL or configuration object.')}else r&&"object"==typeof r&&Object.keys(r).length>0&&(r.title&&"Untitled Project"!==r.title&&e.searchParams.set("title",r.title),r.description&&r.description.length>0&&e.searchParams.set("description",r.description),h.set("config","code/"+(0,n.compressToEncodedURIComponent)(JSON.stringify(r))));if(o&&"object"==typeof o&&Object.keys(o).length>0)try{h.set("params",(0,n.compressToEncodedURIComponent)(JSON.stringify(o)))}catch{Object.keys(o).forEach(t=>{e.searchParams.set(t,encodeURIComponent(String(o[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 i}});var n=s(7294);let o={},r=n.createContext(o);function i(e){let t=n.useContext(r);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(o):e.components||o:i(e.components),n.createElement(r.Provider,{value:t},e.children)}}}]);