"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["5961"],{8930:function(e,n,s){s.r(n),s.d(n,{getPlaygroundUrlDemo:()=>h,sdkDemo:()=>p,default:()=>j,frontMatter:()=>d,metadata:()=>r,assets:()=>c,toc:()=>u,contentTitle:()=>a});var r=JSON.parse('{"id":"sdk/js-ts","title":"JS/TS SDK","description":"This is the core SDK on which others (React, Vue, and Svelte SDKs) are build on top. It is a light-weight (less than 5kb gzipped), zero-dependencies library that allows creating, embedding and communication with LiveCodes playgrounds. It also allows easily creating links to playgrounds.","source":"@site/docs/sdk/js-ts.mdx","sourceDirName":"sdk","slug":"/sdk/js-ts","permalink":"/docs/sdk/js-ts","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/sdk/js-ts.mdx","tags":[],"version":"current","frontMatter":{"title":"JS/TS SDK"},"sidebar":"docsSidebar","previous":{"title":"LiveCodes SDK","permalink":"/docs/sdk/"},"next":{"title":"React SDK","permalink":"/docs/sdk/react"}}'),o=s("5893"),t=s("65"),l=s("3365"),i=s("8500");let d={title:"JS/TS SDK"},a="JavaScript/TypeScript SDK",c={},h={html:`
# Hello World!
Open in playground `},p={js:`import { createPlayground } from "livecodes"; const params = { html: "

Hello World!

", css: "h1 {color: blue;}", js: 'console.log("Hello, LiveCodes!")', console: "open", }; createPlayground('#container', { params }); `,html:'
'},u=[{value:"Installation",id:"installation",level:2},{value:"TypeScript Types",id:"typescript-types",level:2},{value:"createPlayground",id:"createplayground",level:2},{value:"Multiple Sources",id:"multiple-sources",level:3},{value:"getPlaygroundUrl",id:"getplaygroundurl",level:2},{value:"Embed Options",id:"embed-options",level:2},{value:"appUrl",id:"appurl",level:3},{value:"config",id:"config",level:3},{value:"headless",id:"headless",level:3},{value:"import",id:"import",level:3},{value:"loading",id:"loading",level:3},{value:"params",id:"params",level:3},{value:"template",id:"template",level:3},{value:"SDK Methods",id:"sdk-methods",level:2},{value:"load",id:"load",level:3},{value:"run",id:"run",level:3},{value:"format",id:"format",level:3},{value:"getShareUrl",id:"getshareurl",level:3},{value:"getConfig",id:"getconfig",level:3},{value:"setConfig",id:"setconfig",level:3},{value:"getCode",id:"getcode",level:3},{value:"show",id:"show",level:3},{value:"runTests",id:"runtests",level:3},{value:"watch",id:"watch",level:3},{value:"onChange",id:"onchange",level:3},{value:"exec",id:"exec",level:3},{value:"destroy",id:"destroy",level:3},{value:"Styles",id:"styles",level:2},{value:"Default Styles",id:"default-styles",level:3},{value:"Height",id:"height",level:3},{value:"Demo",id:"demo",level:2},{value:"Related",id:"related",level:2}];function g(e){let n={a:"a",admonition:"admonition",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",li:"li",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,t.a)(),...e.components};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(n.header,{children:(0,o.jsxs)(n.h1,{id:"javascripttypescript-sdk",children:["JavaScript/",(0,o.jsx)("wbr",{}),"TypeScript SDK"]})}),"\n","\n",(0,o.jsxs)(n.p,{children:["This is the core SDK on which others (",(0,o.jsx)(n.a,{href:"/docs/sdk/react",children:"React"}),", ",(0,o.jsx)(n.a,{href:"/docs/sdk/vue",children:"Vue"}),", and ",(0,o.jsx)(n.a,{href:"/docs/sdk/svelte",children:"Svelte"})," SDKs) are build on top. It is a light-weight (",(0,o.jsx)(n.a,{href:"https://bundlephobia.com/package/livecodes",children:"less than 5kb gzipped"}),"), zero-dependencies library that allows creating, embedding and communication with LiveCodes playgrounds. It also allows easily creating links to playgrounds."]}),"\n",(0,o.jsx)(n.h2,{id:"installation",children:"Installation"}),"\n",(0,o.jsxs)(n.p,{children:["Please refer to the ",(0,o.jsx)(n.a,{href:"/docs/sdk/#installation",children:"SDK installation"})," section."]}),"\n",(0,o.jsx)(n.admonition,{type:"info",children:(0,o.jsxs)(n.p,{children:["In the full ",(0,o.jsx)(n.a,{href:"/docs/getting-started#standalone-app",children:"standalone app"}),", the JavaScript SDK is accessible via the global variable ",(0,o.jsx)(n.code,{children:"livecodes"}),", which can be interacted with in the browser console."]})}),"\n",(0,o.jsx)(n.h2,{id:"typescript-types",children:"TypeScript Types"}),"\n",(0,o.jsxs)(n.p,{children:["TypeScript types are ",(0,o.jsx)(n.a,{href:"/docs/api/globals",children:"documented here"})," and can be imported from the library."]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-ts",children:"import type { EmbedOptions, Playground } from 'livecodes';\n"})}),"\n",(0,o.jsx)(n.p,{children:"The following 2 functions are exported by the library:"}),"\n",(0,o.jsx)(n.h2,{id:"createplayground",children:(0,o.jsx)(n.code,{children:"createPlayground"})}),"\n",(0,o.jsxs)(n.p,{children:["Type: ",(0,o.jsx)(n.a,{href:"/docs/api/functions/createPlayground",children:(0,o.jsx)(n.code,{children:"(container: string | Element, options?: EmbedOptions) => Promise"})})]}),"\n",(0,o.jsxs)(n.p,{children:["The library exports the function ",(0,o.jsx)(n.code,{children:"createPlayground"})," which has 2 parameters:"]}),"\n",(0,o.jsxs)(n.ul,{children:["\n",(0,o.jsxs)(n.li,{children:[(0,o.jsx)(n.code,{children:"container"})," (required): ",(0,o.jsx)(n.code,{children:"HTMLElement"})," or a string representing a CSS selector. This is the container where the playground is rendered.\nIf not found, an error is thrown (except in ",(0,o.jsx)(n.a,{href:"/docs/sdk/headless",children:"headless mode"}),", in which this parameter is optional and can be omitted)."]}),"\n",(0,o.jsxs)(n.li,{children:[(0,o.jsx)(n.code,{children:"options"})," (optional): an object with embed options (",(0,o.jsx)(n.a,{href:"/docs/api/interfaces/EmbedOptions",children:"EmbedOptions"}),")."]}),"\n"]}),"\n",(0,o.jsxs)(n.p,{children:["The ",(0,o.jsx)(n.code,{children:"createPlayground"})," function returns a promise which resolves to an object that exposes the SDK methods (",(0,o.jsx)(n.a,{href:"/docs/api/interfaces/Playground",children:"Playground"}),")."]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-ts",children:"import { createPlayground, type EmbedOptions } from 'livecodes';\n\nconst options: EmbedOptions = {\n // appUrl: ...\n // config: ...\n // headless: ...\n // import: ...\n // loading: ...\n // params: ...\n // template: ...\n};\n\ncreatePlayground('#container', options).then((playground) => {\n // the `playground` object exposes the SDK methods\n // e.g. playground.run()\n});\n"})}),"\n",(0,o.jsxs)(n.admonition,{title:"Throws",type:"caution",children:[(0,o.jsxs)(n.p,{children:["The ",(0,o.jsx)(n.code,{children:"createPlayground"})," function throws an error (promise is rejected) in any of the following conditions:"]}),(0,o.jsxs)(n.ul,{children:["\n",(0,o.jsxs)(n.li,{children:["The first parameter (",(0,o.jsx)(n.a,{href:"#createplayground",children:(0,o.jsx)(n.code,{children:"container"})}),") is not an element or not found (by CSS selector), except in ",(0,o.jsx)(n.a,{href:"/docs/sdk/headless",children:"headless mode"}),"."]}),"\n",(0,o.jsxs)(n.li,{children:["The embed option ",(0,o.jsx)(n.a,{href:"#appurl",children:(0,o.jsx)(n.code,{children:"appUrl"})})," is supplied and is not a valid URL."]}),"\n",(0,o.jsxs)(n.li,{children:["The embed option ",(0,o.jsx)(n.a,{href:"#config",children:(0,o.jsx)(n.code,{children:"config"})})," is supplied and is not an object or a valid URL."]}),"\n",(0,o.jsxs)(n.li,{children:["Any of the ",(0,o.jsx)(n.a,{href:"#sdk-methods",children:"SDK methods"})," was called after calling the ",(0,o.jsx)(n.a,{href:"#destroy",children:(0,o.jsx)(n.code,{children:"destroy"})})," method."]}),"\n"]})]}),"\n",(0,o.jsx)(n.h3,{id:"multiple-sources",children:"Multiple Sources"}),"\n",(0,o.jsxs)(n.p,{children:["When multiple sources are provided in the ",(0,o.jsx)(n.a,{href:"#embed-options",children:"embed options"}),", each is converted to a ",(0,o.jsx)(n.a,{href:"/docs/configuration/configuration-object",children:"configuration object"})," and the properties are merged.\nIn case there are conflicts between the properties of the configurations, they are overridden in the following order:"]}),"\n",(0,o.jsxs)(n.ul,{children:["\n",(0,o.jsxs)(n.li,{children:[(0,o.jsx)(n.a,{href:"#template",children:(0,o.jsx)(n.code,{children:"template"})})," (lowest precedence)"]}),"\n",(0,o.jsx)(n.li,{children:(0,o.jsx)(n.a,{href:"#import",children:(0,o.jsx)(n.code,{children:"import"})})}),"\n",(0,o.jsx)(n.li,{children:(0,o.jsx)(n.a,{href:"#config",children:(0,o.jsx)(n.code,{children:"config"})})}),"\n",(0,o.jsxs)(n.li,{children:[(0,o.jsx)(n.a,{href:"#params",children:(0,o.jsx)(n.code,{children:"params"})})," (highest precedence)"]}),"\n"]}),"\n",(0,o.jsx)(n.h2,{id:"getplaygroundurl",children:(0,o.jsx)(n.code,{children:"getPlaygroundUrl"})}),"\n",(0,o.jsxs)(n.p,{children:["Type: ",(0,o.jsx)(n.a,{href:"/docs/api/functions/getPlaygroundUrl",children:(0,o.jsx)(n.code,{children:"(options?: EmbedOptions) => string"})})]}),"\n",(0,o.jsxs)(n.p,{children:["Gets the URL to playground (as a string) from the provided ",(0,o.jsx)(n.a,{href:"#embed-options",children:"options"}),". This can be useful for providing links to run code in playgrounds."]}),"\n",(0,o.jsx)(n.p,{children:"Example:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-html",children:'
# Hello World!
\nOpen in playground\n `,m=`
`.trimStart();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(i,{className:`container_Egsj ${e.className}`,style:{height:l||"50vh",...e.style},appUrl:d.G,...e,config:{theme:c,themeColor:"hsl(215, 8%, 60%)",..."object"==typeof e.config?e.config:{}}}),!1!==e.showCode&&(0,r.jsx)(j,{js:p,ts:u,react:g,vue:x,svelte:m})]})}},8500:function(e,n,s){s.d(n,{Z:()=>a});var r=s("5893");s("7294");var o=s("6735");function t(e){let{children:n,fallback:s}=e;return(0,o.Z)()?(0,r.jsx)(r.Fragment,{children:n?.()}):s??null}var l=s("1705"),i=s("8294"),d=s("1858");function a(e){let{params:n,config:s,code:o,language:a="js",codeTitle:c="",showLineNumbers:h=!1,formatCode:p=!0,linkText:u="Run in LiveCodes",style:g={},className:j=""}=e,x=(0,i.r)({appUrl:d.G,params:n,config:s});return(0,r.jsxs)("div",{style:{marginBottom:"30px",...g},className:j,children:[o&&(0,r.jsx)(t,{children:()=>(0,r.jsx)(l.Z,{language:a,title:c,showLineNumbers:h,children:p?function(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"js";return window.prettier?.format(e,{parser:"html"===n?"html":"babel",plugins:window.prettierPlugins})}(o,a):o})}),(0,r.jsxs)("a",{href:x,target:"_blank",rel:"noreferrer",children:[u,(0,r.jsx)("svg",{width:"12",height:"12","aria-hidden":"true",viewBox:"0 0 24 24",className:"iconExternalLink_node_modules-@docusaurus-theme-classic-lib-theme-Icon-ExternalLink-styles-module",style:{marginLeft:"4px"},children:(0,r.jsx)("path",{fill:"currentColor",d:"M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"})})]})]})}},8294:function(e,n,s){s.d(n,{T:function(){return o},r:function(){return t}});var r=s(7728);async function o(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"object"!=typeof e||e instanceof HTMLElement||!e.headless&&"headless"!==e.view||(n=e,e=null);let{config:s={},headless:r,loading:o="lazy",view:l}=n,i=r||"headless"===l,d=null,a=null;if("string"==typeof e)d=document.querySelector(e);else if(e instanceof HTMLElement)d=e;else if(!(i&&"object"==typeof e))throw Error("A valid container element is required.");if(!d){if(i)S(d=document.createElement("div")),document.body.appendChild(d);else throw Error(`Cannot find element: "${e}"`)}let c=new URL(t(n)),h=c.origin;c.searchParams.set("embed","true"),c.searchParams.set("loading",i?"eager":o),c.searchParams.set("sdkVersion",process.env.SDK_VERSION||"latest"),"object"==typeof s&&Object.keys(s).length>0&&c.searchParams.set("config","sdk");let p=n.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,g="Cannot call API methods after calling `destroy()`.",j=await new Promise(e=>{if(!d)return;let n=d.dataset.height||d.style.height;if(n&&!i){let e=isNaN(Number(n))?n:n+"px";d.style.height=e}"false"===d.dataset.defaultStyles||i||(d.style.backgroundColor||="#fff",d.style.border||="1px solid black",d.style.borderRadius||="8px",d.style.boxSizing||="border-box",d.style.padding||="0",d.style.width||="100%",d.style.height||=d.style.height||"300px",d.style.minHeight="200px",d.style.flexGrow="1",d.style.overflow||="hidden",d.style.resize||="vertical");let r="livecodes",t=d.querySelector(`iframe.${r}`),l=t||document.createElement("iframe");l.classList.add(r),l.setAttribute("allow","accelerometer; camera; encrypted-media; display-capture; geolocation; gyroscope; microphone; midi; clipboard-read; clipboard-write; web-share"),l.setAttribute("allowtransparency","true"),l.setAttribute("allowpaymentrequest","true"),l.setAttribute("allowfullscreen","true"),l.setAttribute("sandbox","allow-same-origin allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts"),l.setAttribute("loading","eager"===o?"eager":"lazy"),i?S(l):(l.style.height="100%",l.style.minHeight="200px",l.style.width="100%",l.style.margin="0",l.style.border="0",l.style.borderRadius=d.style.borderRadius),addEventListener("message",function e(n){n.source===l.contentWindow&&n.origin===h&&n.data?.type==="livecodes-init"&&(removeEventListener("message",e),a=Number(n.data.payload.appVersion.replace(/^v/,"")))}),(!a||a<46)&&addEventListener("message",function e(n){n.source===l.contentWindow&&n.origin===h&&n.data?.type==="livecodes-get-config"&&(removeEventListener("message",e),l.contentWindow?.postMessage({type:"livecodes-config",payload:s},h))}),l.onload=()=>{e(l)},l.src=c.href,t||d.appendChild(l)}),x=new Promise(e=>{addEventListener("message",function n(s){s.source===j.contentWindow&&s.origin===h&&s.data?.type==="livecodes-ready"&&(removeEventListener("message",n),e(),x.settled=!0)})}),m=()=>u?Promise.reject(g):new Promise(async e=>{x.settled&&e(),j.contentWindow?.postMessage({type:"livecodes-load"},h),await x,e()}),f=(e,n)=>new Promise(async(s,r)=>{if(u)return r(g);await m();let o=k();addEventListener("message",function n(t){if(t.source===j.contentWindow&&t.origin===h&&t.data?.type==="livecodes-api-response"&&t.data?.id===o&&t.data.method===e){removeEventListener("message",n);let e=t.data.payload;e?.error?r(e.error):s(e)}}),j.contentWindow?.postMessage({method:e,id:o,args:n},h)}),y={},v=["load","ready","code","console","tests","destroy"],w=(e,n)=>{if(u)throw Error(g);return v.includes(e)?(f("watch",[e]),y[e]||(y[e]=[]),y[e]?.push(n),{remove:()=>{y[e]=y[e]?.filter(e=>e!==n),y[e]?.length===0&&f("watch",[e,"unsubscribe"])}}):{remove:()=>void 0}},b=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 n=b(e.data?.type??"");if(e.source!==j.contentWindow||e.origin!==h||!n||!y[n])return;let s=e.data?.payload;y[n]?.forEach(e=>{e(s)})});let P=()=>{Object.values(y).forEach(e=>{e.length=0}),j?.remove?.(),u=!0};function S(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,n)=>{e.forEach(async e=>{e.isIntersecting&&(await m(),n.unobserve(d))})},{rootMargin:"150px"}).observe(d);let k=()=>(String(Math.random())+Date.now().toFixed()).replace("0.","");return{load:()=>m(),run:()=>f("run"),format:e=>f("format",[e]),getShareUrl:e=>f("getShareUrl",[e]),getConfig:e=>f("getConfig",[e]),setConfig:e=>f("setConfig",[e]),getCode:()=>f("getCode"),show:(e,n)=>f("show",[e,n]),runTests:()=>f("runTests"),onChange:e=>w("code",e),watch:w,exec:function(e){for(var n=arguments.length,s=Array(n>1?n-1:0),r=1;rx.settled?f("destroy").then(P):u?Promise.reject(g):(P(),Promise.resolve())}}function t(){let e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{appUrl:s="https://livecodes.io",params:o={},config:t={},headless:l,import:i,lite:d,view:a,...c}=n;try{e=new URL(s)}catch{throw Error(`${s} is not a valid URL.`)}let h=new URLSearchParams;Object.entries(c).forEach(n=>{let[s,r]=n;void 0!==r&&e.searchParams.set(s,String(r))});let p="headless"===n.view||l;if(d&&(console.warn('Deprecation notice: "lite" option is deprecated. Use "config: { mode: \'lite\' }" instead.'),"object"==typeof t&&null==t.mode?t.mode="lite":e.searchParams.set("lite","true")),a&&(console.warn('Deprecation notice: The "view" option has been moved to "config.view". For headless mode use "headless: true".'),"object"==typeof t&&null==t.view&&"headless"!==a?t.view=a:e.searchParams.set("view",a)),"string"==typeof t)try{new URL(t),e.searchParams.set("config",encodeURIComponent(t))}catch{throw Error('"config" is not a valid URL or configuration object.')}else t&&"object"==typeof t&&Object.keys(t).length>0&&(t.title&&"Untitled Project"!==t.title&&e.searchParams.set("title",t.title),t.description&&t.description.length>0&&e.searchParams.set("description",t.description),h.set("config","code/"+(0,r.compressToEncodedURIComponent)(JSON.stringify(t))));if(o&&"object"==typeof o&&Object.keys(o).length>0)try{h.set("params",(0,r.compressToEncodedURIComponent)(JSON.stringify(o)))}catch{Object.keys(o).forEach(n=>{e.searchParams.set(n,encodeURIComponent(String(o[n])))})}return i&&e.searchParams.set("x",encodeURIComponent(i)),p&&e.searchParams.set("headless","true"),e.hash=h.toString(),e.href}},65:function(e,n,s){s.d(n,{Z:function(){return i},a:function(){return l}});var r=s(7294);let o={},t=r.createContext(o);function l(e){let n=r.useContext(t);return r.useMemo(function(){return"function"==typeof e?e(n):{...n,...e}},[n,e])}function i(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(o):e.components||o:l(e.components),r.createElement(t.Provider,{value:n},e.children)}}}]);